How to set auto_ptr to NULL
-
26-06-2021 - |
سؤال
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.