Reputation: 2782
I am new to C++
and implemented the following struct
:
struct Person {
String name;
int age;
};
Now I create a new object:
Person *p = new Person();
p->name = "name";
p->age = 211;
and push
it onto a stack
:
stack.push(*p);
I have a while(!stack.empty())
expression and in there I process every element I pushed onto the stack.
Now where do I free the memory? In the while
-loop I do the following:
Person *current = &stack.front();
stack.pop();
// do stuff
delete current;
Sadly, the delete current
statement throws some kind of exception.
What do I do wrong? Thanks for your help.
Upvotes: 1
Views: 151
Reputation: 227468
You would need to delete p
after pushing into the stack. The stack stores its own copy of the object pushed into it, so there is no need to do anything to it after popping.
But the real solution is to not use new
in the first place:
Person p = {"name", 211};
...
stack.push(p);
or just
stack.push(Person{"name", 211});
Then
Person current = stack.front();
stack.pop();
So, no need to deal directly with memory management.
Upvotes: 8
Reputation: 11018
You don't need to make a pointer. If you have to, then use a smart pointer to free the memory for you: std::unique_ptr<Person> p(new Person);
Upvotes: 0
Reputation: 308412
When you push something on to a stack, you don't push the original object - you push a copy of the object. To free the memory of the original object, you need to do it right at the point after you've pushed it.
Or you can skip that altogether and don't use new
to create the object in the first place:
Person p;
p.name = "name";
p.age = 211;
stack.push(p);
Upvotes: 4