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_ptrconstructor that takes a pointer is explicit, to help prevent accidentally transferring ownership to anstd::auto_ptr. You can pass in two default-constructedstd::auto_ptrobjects:If the Standard Library implementations you are targeting include
std::unique_ptr, consider using that instead. It does not have the problematic copy semantics ofstd::auto_ptr, sostd::auto_ptrhas been deprecated and replaced bystd::unique_ptr.std::unique_ptralso has a converting constructor that allows implicit conversion from a null pointer constant, so your code passingNULLwould work just fine if you were usingstd::unique_ptr.