function - memory management error in C++ -


i have doubts following test snippet. use node pointer point node instance returned function test2. why delete failed ?

any comments 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 write

    node n = test2(m); 

n not reference node created test2. copy of it. node created test2 leaked. need:

    node& n = test2(m); 

as aside: assume exercise understand references , pointers. real program, want write:

std::unique_ptr<node> test4(const node& n) {     std::unique_ptr<node> result{new node};     result->a = n.a + 5;     return result; } 

or 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, don't need bother deleting allocated node - compiler when unique_ptr in calling code goes out of scope.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -