C ++ array constructor

I'm just wondering if an element of the class array can be created immediately after building the class:

class C
{
      public:
          C(int a) : i(a) {}

      private:
          int i;
};

class D
{
 public:
        D() : a(5, 8) {}
        D(int m, int n) : a(m,n) {}

     private:
     C a[2];

};

As far as I have googled, creating an array inside the Constructor, for example above, is not possible in C ++. Alternatively, an array element may be initialized inside a constructor block as follows.

class D
    {
     public:
         D() { 
               a[0] = 5;
               a[1] = 8; 
             }
         D(int m, int n) { 
                           a[0] = m;
                           a[1] = n; 
                         }
         private:
         C a[2];

    };

But then this is not the creation of an array, but the purpose of the array. Array elements are automatically created by the compiler through their default constructor, and then they are manually assigned to specific values ​​inside the C'tor block. What is annoying; for such a workaround, class C should offer a default constructor.

- , . , std::vector , - - , Boost .

+5
2

- , , ++, C, , . , , ( ?!?!?) - a C, C, , " " ( C, , ).

+5

. ; , .

#include <iostream>
using namespace std;

template< class T, int N >
struct constructed_array {
        char storage[ sizeof( T[N] ) ]; // careful about alignment
        template< class I >
        constructed_array( I first ) {
                for ( int i = 0; i < N; ++ i, ++ first ) {
                        new( &get()[i] ) T( *first );
                }
        }
        T *get() const { return reinterpret_cast< T const* >( storage ); }
        T *get() { return reinterpret_cast< T * >( storage ); }
        operator T *() const { return get(); }
        operator T *() { return get(); }
};

char const *message[] = { "hello", ", ", "world!" };

int main( int argc, char ** argv ) {
        constructed_array< string, 3 > a( message );
        for ( int i = 0; i < 3; ++ i ) {
                cerr << a[i];
        }
        cerr << endl;
        return 0;
}
+1
source

All Articles