c++ - 将对象指针的数据成员数组初始化为正确的大小和 null

标签 c++ arrays heap-memory

我有一个简单的 C++ Node 类,它包含指向同一类型的指针的数组数据成员。这个数组是动态分配的,它的指针应该默认为 null 但我不确定如何实现它。

class Node
{
private:
    Node *_nextNode[];
    string _data;
}

Node::Node( const string &p_data, const int &p_levels ): _data(p_data)
{
   //unsure how to initialize the '_nextNode[]' member so that the size of the array is of p_levels and they all default to null pointers 
}

class SkipList
{
    private:

}

最佳答案

使用 std::vector<Node*> :

Node::Node( const string &p_data, const int &p_levels ): 
    _data(p_data),
    _nextNode(p_levels)
{

这将初始化 _nextNode 的元素至 nullptr

考虑使用 smart pointer implementation而不是 Node*管理 Node 的销毁实例给你。


如果你必须使用 Node*那么你需要一个Node**指向 Node* 的列表:

class Node
{
private:
    Node**_nextNode;
    string _data;
};

Node::Node( const string &p_data, const int &p_levels ): 
    _data(p_data),
    _nextNode(new Node*[p_levels]())
{                              //^^ value initialization.

分配 int* 的数组包含 p_levels元素和值初始化它们(将它们设置为 NULL )。 Node需要知道 _nextNode 中存储了多少元素所以p_levels还需要存储。销毁:

for (int i = 0; i < _nextNodeElements; i++)
{
    delete _nextNode[i]; // delete NULL is safe, a no-op.
}
delete[] _nextNode;

只为将你推向std::vector再次:std::vector<std::unique_ptr<Node>> _nextNode;不需要手写的析构函数,默认生成的析构函数就足够了。

关于c++ - 将对象指针的数据成员数组初始化为正确的大小和 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16378612/

相关文章:

c++ - 使用 std::search 搜索 std::string 中的子字符串

javascript - 在 JavaScript 中创建网格数组

c - 根据长度崩溃对静态数组中的字符串进行排序? |错误分配/访问|

ios - 线程 1 : Fatal error: Index out of range. 无法快速从数组中获取值,控制台显示它们不是空数组

java - 如何动态监控 Java 堆大小?

.net - 如何探索 .NET 应用程序中的托管堆来识别可能的内存优化?

c - 指针与堆中内存的关系

c++ - SQLite3 错误无法打开数据库文件

c++ - 赋值 null 时不兼容的类型

c++ - 双二分查找算法