指向c ++类和初始化的指针

时间:2016-08-10 09:51:21

标签: c++ arrays class pointers

我需要创建一个指向C ++类的指针数组,让我们将它称为A类,它应该是同一个类的静态元素:

class A{

public:
  static A** array;
}

该数组的元素数量未知。如何为该阵列分配和重新分配内存?

1 个答案:

答案 0 :(得分:0)

使用原始指针:

以下代码只是为了解释。

size_t num_elem = 123;  // Dynamic number of elements

// Allocation
A::array = new A*[num_elem];  // Dynamic Allocation
for (size_t i = 0; i < num_elem; ++i) {
  A::array[i] = new A();  // Allocation of each A in the array.
}

// Deallocation
for (size_t i = 0; i < num_elem; ++i) {
 delete A::array[i];  // Dealloce each instance of A.
}
delete[] A::array;  // Deallocation
A::array = nullptr;  // Safety reason

使用矢量容器和智能指针

正如一些评论建议的那样,这是一种更安全的方式。

编辑我假设你需要一个数组数组,A也必须动态分配。此外,为了更安全,我建议您使用smart pointer

#include <vector>
#include <memory>

// ...
size_t num_elem = 123;  // Dynamic number of elements
std::vector<std::unique_ptr<A>> array(num_elem);  // Now array contains 123 pointers to A.


// Allocation
for (size_t i = 0; i < num_elem; ++i) {
  array[i] = std::make_unique<A>(/*obj contruction*/);  // Allocation of each A in the array.
}

// Deallocation
array.clear();
相关问题