【问题标题】:C++ dynamic allocation of class arrayC++动态分配类数组
【发布时间】:2015-10-22 14:36:42
【问题描述】:

假设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 由用户在运行时输入。

编辑: 我想实现的目标不可能如 zenith 所回答的那样,否则将太复杂。那么我怎样才能使用std::vector呢?

【问题讨论】:

  • 为什么不std::vector?
  • 学校作业..不能使用 STL。
  • 编辑:std::vector<X> xs(sizeOfArray, X(1, 2));
  • @Pushkar:如果您想对 zenith 的回答进行澄清,请在对他的回答的评论中这样做。也就是说,^Jarod42 的评论是正确的。

标签: c++ dynamic-allocation


【解决方案1】:

这似乎是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

【讨论】:

  • std::aligned_storage 可能会有所帮助。但是std::vector 更简单。
  • std::aligned_storage 确实很有趣。从std::vector 开始,OP 不得使用它。此外,我认为std::vector does use placement new.
  • 查看编辑。我可能会尝试std::vector,因为这看起来太复杂了
  • 我通过类的setter函数分配内存。函数返回后数据是否会保留在内存中?
  • @OP 除非你提供实际代码sn-ps你所做的,否则我恐怕无法给你一个相关的答案。
【解决方案2】:

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

  • 您为每个元素提供一个初始化程序,或者
  • 您使用vector。

见:

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • SizeOfArray 由用户在运行时输入
    猜你喜欢
    • 2021-11-24
    • 2014-08-19
    • 2012-11-23
    • 2010-10-02
    • 1970-01-01
    • 2017-05-07
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多