Ryan's District Boards

Computer, programming, and webmaster help , support , tips and tricks => Tutorials Zone! => Internet webmaster computer programming technology tips and tricks => C++ / C / C# ....Tutorials => Topic started by: ben2ong2 on October 06, 2006, 06:08:46 PM

Title: c++ array tips - Another look at array initialization
Post by: ben2ong2 on October 06, 2006, 06:08:46 PM
RESPONSE: jamshid (Jamshid Afshar), 15 Jul 94

[...]

I think a better alternative to the "pass constructor
parameters to array elements" problem is to use an array class that
explicitly constructs and destroys the elements itself using
placement-new:

   #include <new.h>

   class ComplexArray {
       complex* arr;
       int sz;
   public:
      ComplexArray( int size, const complex& init ) {
         arr = operator new( size*sizeof(complex) );  // get raw memory
         sz = size;
         for (int i=0; i<size; ++i)
            new (arr+i) complex( init ); // copy construct each element
      }
      ~ComplexArray() {
         while (sz--)
            arr[sz].~complex();   // destruct each element
         operator delete( arr );  // return raw memory to the heap
      }
   };

   ComplexArray a( 10, complex(-1,7) );

ComplexArray could be made a template by replacing "complex" with T.
If you want to be able to initialize the array elements with multiple
constructor arguments, I think you could use the new "member
templates":

   template<class T>
   class Array {
      T* arr;   
      int sz;
   public:
      Array(int size, const T& init);

      template<class P1, class P2>
      Array(int size, const P1& p1, const P2& p2) {
          //...like above
             new (arr+i) T(p1, p2); // uses ctor other than copy-ctor
      }
   };

[...]