3

有没有办法将 auto_ptr 设置为 NULL 或等效项?例如,我正在创建一个由节点对象组成的二叉树:

struct Node {
    int weight;
    char litteral;
    auto_ptr<Node> childL;
    auto_ptr<Node> childR;
    void set_node(int w, char l, auto_ptr<Node> L, auto_ptr<Node> R){
        weight = w;
        litteral = l;
        childL = L;
        childR = R;
    }
};

对于不是父节点的节点,我计划这样做:

auto_ptr<Node> n(new Node);
(*n).set_node(i->second, i->first, NULL, NULL);

这会引发错误。有没有办法将其设置为 NULL,或者是否有其他有意义的行动方案?

4

2 回答 2

6

采用指针的std::auto_ptr构造函数是显式的,以帮助防止意外将所有权转移到std::auto_ptr. 您可以传入两个默认构造的std::auto_ptr对象:

(*n).set_node(i->second, i->first, std::auto_ptr<Node>(), std::auto_ptr<Node>());

如果您的目标标准库实现包括std::unique_ptr,请考虑改用它。它没有 有问题的复制语义std::auto_ptr,因此std::auto_ptr已被弃用并被std::unique_ptr.

std::unique_ptr还有一个转换构造函数,允许从空指针常量进行隐式转换,因此NULL如果您使用std::unique_ptr.

于 2012-08-15T18:19:50.430 回答
2

如果您的编译器工具集支持它(例如 Visual C++ 10/11、Gcc 4.5?或更高版本),或者使用 boost::scoped_ptr(如果您使用 Visual C++ 9 或更早版本以及最新版本,我建议切换到 std::unique_ptr boost),以避免 std::auto_ptr 的基本复制语义问题。

注意:std::unique_ptr 是一个 C++11 特性,它可能对选择编译器有额外的要求。

于 2012-08-15T19:11:41.757 回答