C ++动态分配类数组

时间:2015-10-22 14:36:42

标签: c++ dynamic-allocation

假设class X具有构造函数X(int a, int b)

我创建一个指向X的指针X *ptr;,为类动态分配内存。

现在创建一个X类对象数组

 ptr = new X[sizeOfArray];

直到现在一切都很好。但我想要做的是创建上面的对象数组应该调用构造函数X(int a, int b)。我尝试如下:

ptr = new X(1,2)[sizeOfArray]; 

正如所料,它给了我编译时错误

  

错误:预期';'之前' ['令牌|

如何创建一个对象数组来调用构造函数?

用户在运行时输入

SizeOfArray

修改 我想要达到的目标是不可能的,如天顶所回答的那样,或者太复杂了。那么我怎样才能使用std::vector呢?

3 个答案:

答案 0 :(得分:5)

这似乎是placement new ...

的工作

这是一个基本的例子:

Run It Online !

#include <iostream>
#include <cstddef>  // size_t
#include <new>      // placement new

using std::cout;
using std::endl;

struct X
{
    X(int a_, int b_) : a{a_}, b{b_} {}
    int a;
    int b;
};

int main()
{
    const size_t element_size   = sizeof(X);
    const size_t element_count  = 10;

    // memory where new objects are going to be placed
    char* memory = new char[element_count * element_size];

    // next insertion index
    size_t insertion_index = 0;

    // construct a new X in the address (place + insertion_index)
    void* place = memory + insertion_index;
    X* x = new(place) X(1, 2);
    // advance the insertion index
    insertion_index += element_size;

    // check out the new object
    cout << "x(" << x->a << ", " << x->b << ")" << endl;

    // explicit object destruction
    x->~X();

    // free the memory
    delete[] memory;
}

编辑:如果我理解了你的编辑,你想做这样的事情:

Run It Online !

#include <vector>
// init a vector of `element_count x X(1, 2)`
std::vector<X> vec(element_count, X(1, 2));

// you can still get a raw pointer to the array as such
X* ptr1 = &vec[0];
X* ptr2 = vec.data();  // C++11

答案 1 :(得分:4)

这在当前的C ++标准中是不可能的,除非:

  • 您为每个元素提供初始值设定项,或
  • 您使用vector

请参阅:

答案 2 :(得分:0)

你不能说sizeOfArray是变量还是常量。如果它是(小)常量,则可以在C ++ 11中执行此操作:

X* ptr = new X[3] { {1,2}, {1,2}, {1,2} };