在堆上分配指针数组

时间:2017-11-14 18:56:40

标签: c++ arrays heap

以下是创建x个新对象,还是只为x对象分配空间?:

{
    part: 1, 
    data: [arrayBuffer] 
} 

我需要为堆上的x Vector3D对象构建一个带空格的数组。但是,只有在"添加"时才能创建Vector3D对象。函数被调用 - 这将获取参数,在堆上构造对象并将其地址添加到Vector3D指针数组。

2 个答案:

答案 0 :(得分:4)

这会在堆上创建一个Vector3D对象数组。

通过调用Vector3D构造函数创建每个向量。

在Vector3D的默认构造函数中放置一个小的调试print语句,并观察构造函数的调用次数与数组中的向量相同。

示例:

#include <iostream>
using namespace std;

class C {
public:
  C() { cout << "Hello default constructor here\n"; }
};

int main() {
  C* cs = new C[5];
}

输出是:

Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here
Hello default constructor here

如果您的类没有默认构造函数,则无法一次性分配数组(感谢评论@Everyone),因此在这种情况下请考虑使用std::vectorstd::array并动态添加你的Vector3D对象 - 甚至&#34;静态&#34;!例如:

#include <iostream>
#include <vector>
using namespace std;

class Vector3D {
  double i, j, k;
public:
  Vector3D(double i, double j, double k): i(i), j(j), k(k) {}
};

int main() {
  vector<Vector3D> v = {
    Vector3D(3, 4, 5),
    Vector3D(6, 8, 10),
    Vector3D(7, 24, 25)
  };
  v.push_back(Vector3D(1, 2, 3));
  cout << v.size() << '\n';
}

输出4。

您还可以使矢量包含指向Vector3D对象的指针。

答案 1 :(得分:0)

根据提问者对RayToal优秀答案的评论添加。如果您在运行时之前不知道binArray的大小,则必须使用std::vector。如果您想单独分配每个项目,我建议您使用std::vector<Vector3D*>

通过这种方式,您可以在运行时调整std::vector的大小,当您执行此操作时,它将保留一堆未分配的nullptr。然后你可以分别分配它们中的每一个。

std::vector<Vector3D*> binArray;
binArray.resize(x);  // now you have binArray of size x and no allocated elements
binArray[0] = new Vector3D(...);

请记住,在您不使用它们之后需要删除它们以避免内存泄漏:

for(size_t i=0;i<binArray.size(); i++)
  if(binArray[i]!=nullptr) delete binArray[i];
相关问题