【问题标题】:pointer to pointer to c++ class and initialization指向 C++ 类的指针和初始化的指针
【发布时间】:2016-08-10 09:51:20
【问题描述】:

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

class A{

public:
  static A** array;
}

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

【问题讨论】:

  • 首先,每当您需要“动态数组”时,您的下一个想法应该是std::vector
  • 你为什么不使用 std::vectorcplusplus.com/reference/vector/vector
  • @noob 因为“A** 和使用一些新的和删除”。
  • @noob 在编写代码之前不要尝试优化代码并有效地衡量它需要优化
  • @noob 按照这个逻辑,你应该用机器语言编程。使用更高的抽象(例如std::vector)。好处是巨大的,开销是最小的

标签: c++ arrays class pointers


【解决方案1】:

使用原始指针:

下面的代码只是为了解释。

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

带有向量容器和智能指针

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

编辑我假设您需要一个数组数组,并且 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();

【讨论】:

  • 不仅仅是 / 更简单。最重要的是,它是更安全的方式。在std::vector 示例中,您仍在使用newdelete。要了解为什么要避免手动内存管理(即显式调用 new),请告诉我当 A 的构造函数在循环分配中间抛出时会发生什么。你看到内存泄漏了吗?
  • @bolov 是的!反正他们是指针。您可以使用std::unique_ptr&lt;A&gt; 以使其更安全,但答案是 OT。
  • 您已经隐含地假设类也需要动态分配。这可以很容易地成为一个简单的实例跟踪设备。
猜你喜欢
  • 1970-01-01
  • 2016-11-09
  • 2010-10-11
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
相关资源
最近更新 更多