Pus*_*kar 4 c++ dynamic-allocation
假设a class X具有构造函数X(int a, int b)
我创建了一个指向X的指针,X *ptr;为类动态分配内存.
现在创建一个X类对象数组
ptr = new X[sizeOfArray];
Run Code Online (Sandbox Code Playgroud)
到现在一切都很好.但我想要做的是创建上面的对象数组应该调用构造函数X(int a, int b).我尝试如下:
ptr = new X(1,2)[sizeOfArray];
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,它给了我编译时错误
错误:预期';' 在'['标记|之前
如何创建一个对象数组来调用构造函数?
SizeOfArray 用户在运行时输入.
编辑:
我想要达到的目标是不可能的,如天顶所回答的那样,或者太复杂了.那我std::vector该如何使用呢?
这是一个基本的例子:
#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 Code Online (Sandbox Code Playgroud)
编辑:如果我理解你的编辑,你想做这样的事情:
#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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |