문제

Is there a way to set an auto_ptr to NULL, or the equivalent? For instance, I'm creating a binary tree composed of node objects:

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;
    }
};

For an node that is not the parent node, I had planned on doing this:

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

This throws an error. Is there any way to set it to NULL, or is there another course of action that would make sense?

도움이 되었습니까?

해결책

The std::auto_ptr constructor that takes a pointer is explicit, to help prevent accidentally transferring ownership to an std::auto_ptr. You can pass in two default-constructed std::auto_ptr objects:

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

If the Standard Library implementations you are targeting include std::unique_ptr, consider using that instead. It does not have the problematic copy semantics of std::auto_ptr, so std::auto_ptr has been deprecated and replaced by std::unique_ptr.

std::unique_ptr also has a converting constructor that allows implicit conversion from a null pointer constant, so your code passing NULL would work just fine if you were using std::unique_ptr.

다른 팁

I would recommend switching to std::unique_ptr if your compiler toolset supports it (e.g. Visual C++ 10/11, Gcc 4.5? or later), or using boost::scoped_ptr (if you are with Visual C++ 9 or earlier and a recent version of boost), to avoid the fundamental copying semantic issues with std::auto_ptr.

Note: std::unique_ptr is a C++11 feature which may impose extra requirements for choosing your compiler.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top