I have doubts about the following test snippet. I use a Node pointer to point the node instance returned by function test2. Why the delete failed ?
Any comments would be appreciated. thanks!
struct Node
{
int a;
};
Node& test2(Node &n)
{
Node *p = new Node;
p->a = n.a + 5;
return *p;
}
Node* test3(Node &n)
{
Node *p = new Node;
p->a = n.a + 5;
return p;
}
int main()
{
Node m;
m.a = 12;
Node n = test2(m);
Node *x = test3(n);
cout << m.a << ";" << n.a << ";" << x->a << endl;
delete x; //OK
x = &n;
delete x; //Error
return 0;
}
When you write
Node n = test2(m);
n
is not a reference to the Node
created by test2
. It is a copy of it. The Node
created by test2
is leaked. You need:
Node& n = test2(m);
As an aside: I assume this is an exercise to understand references and pointers. For a real program, you would always want to write:
std::unique_ptr<Node> test4(const Node& n)
{
std::unique_ptr<Node> result{new Node};
result->a = n.a + 5;
return result;
}
or even better:
std::unique_ptr<Node> test4(const Node& n)
{
auto result = std::make_unique<Node>();
result->a = n.a + 5;
return result;
}
With either of these solutions, you don't need to bother about deleting the allocated Node
- the compiler will do that for you when the unique_ptr in your calling code goes out of scope.
test2
returns a reference of a Node
object that's copied (or moved) to n
because n
is not a reference. This object now resides on the stack, calling delete
on objects on the stack is illegal.
Why the delete failed ?
Here
x = &n;
delete x; //Error
you are assigning an address of a local variable
Node n = test2(m);
which can't (neither needs to) be handled by delete
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.