News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ array tips - Another look at array initialization

Started by ben2ong2, October 06, 2006, 06:08:46 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

ben2ong2

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
      }
   };

[...]

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login