如何使用参数化构造函数动态分配对象数组?

uba*_*uba 4 c++ dynamic-allocation

考虑一个简单的类:

class SimpleClass {
    int a;
public:
    SimpleClass():a(0){}
    SimpleClass(int n):a(n){}
    // other functions
};

SimpleClass *p1, *p2;

p1 = new SimpleClass[5];

p2 = new SimpleClass(3);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,SimpleClass()将调用默认构造函数来构造p1的新分配对象和p2的参数化构造函数.我的问题是:是否可以使用new运算符分配数组并使用参数化构造函数?例如,如果我希望使用变量a值分别为10,12,15,...的对象初始化数组,是否可以在使用new运算符时传递这些值?

我知道使用stl向量是处理对象数组的更好主意.我想知道上面是否可以使用new来分配一个数组.

Naw*_*waz 7

你可以使用placement-new作为:

typedef std::aligned_storage<sizeof(SimpleClass), 
                             std::alignment_of<SimpleClass>::value
                             >::type storage_type;

//first get the aligned uninitialized memory!
SimpleClass *p1 = reinterpret_cast<SimpleClass*>(new storage_type[N]);

//then use placement new to construct the objects
for(size_t i = 0; i < N ; i++)
     new (p1+i) SimpleClass(i * 10);
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我正在传递(i * 10)给构造函数SampleClass.

希望有所帮助.