在结构中创建智能指针?

Creating a smart pointer in a struct?

我正在使用结构对二叉树中的节点建模。在结构中,我试图有一个指向左右 child 的指针。

问题是,由于我创建结构的方式,我一直 运行 进入堆栈溢出。看来我一直在处理智能指针的方式不断地在堆栈上分配内存。

当我在 main.c 中创建 root 时专门抛出异常。

我是智能指针的新手(我一直在使用原始指针,我最近了解到这在 C++ 中是一种不好的做法),我曾尝试自己解决这个问题,但没有成功。

有人可以批评我的 struct/smart 指针使用吗?非常感谢。

#include <iostream> 
#include <memory> 

//Node struct 
struct Node
{
    int data;
    std::unique_ptr<Node> left;
    std::unique_ptr<Node> right;

    Node(int data) {
        this->data = data;
        this->left = std::make_unique<Node>(NULL);
        this->right = std::make_unique<Node>(NULL); 
    }

};

//insert Node into binary search tree
void insert(int data, std::unique_ptr<Node>& root)
{
    if (root == NULL)
    {
        root = std::make_unique<Node>(data);
    }
    else {
        if (root->data > data)
        {
            insert(data, root->left);
        }
        else {
            insert(data, root->right);
        }
    }
}

//In Order tree traversal 
void inOrderTraversal(std::unique_ptr<Node>& root)
{
    if (root == NULL) return; 

    inOrderTraversal(root->left); 

    std::cout << root->data << std::endl; 

    inOrderTraversal(root->right); 
}

int main()
{
    //Initialize root to NULL
    std::unique_ptr<Node> root = std::make_unique<Node>(NULL);


    insert(20, root); 
    insert(50, root);
    insert(30, root);
    insert(5, root);
    insert(6, root);
    insert(99, root);
    insert(77, root);
    insert(56, root);
    insert(32, root);
    inOrderTraversal(root); 

    return 0; 
}

用 nullptr 替换所有 NULL,不要使用 std::make_unique(NULL);

Node::Node(int data) {
    this->data = data;
    this->left = nullptr;
    this->right = nullptr;
}



int main()
{
    //Initialize root to NULL
    std::unique_ptr<Node> root = nullptr;

        // other codes ..
}

The function std::make_unique<Node> 接受参数转发 Node 构造函数。

在 C 和 C++ 中,NULL 通常只是 0 的宏。

因此,当您调用 std::make_unique<Node>(NULL); 时,您正在使用 data = 0.

初始化 Node

然后递归调用this->left = std::make_unique<Node>(NULL);,最终导致无限递归和堆栈溢出。

要解决这个问题,您可以分配 std::unique_ptr<Node> left = NULL.

我还建议使用 nullptr 代替 NULL,因为它是类型安全的。只需将代码中的 NULL 替换为 nullptr 就会出现编译器错误,从而帮助您解决问题。

error: no matching constructor for initialization of 'Node'