Class's member is an Object that changes
Jan 15, 2012 at 9:18am UTC
I have a class that has a pointer to another object as one of its members.
The class has a method that will reassign another instance of the object.
for example:
1 2 3 4 5 6 7 8 9 10 11 12 13
class A
{
public :
void reassign();
private :
B* bPointer;
}
void A::reassign()
{
B newB;
bPointer = &newB;
}
I'm wondering if this will cause memory problems during run-time if I call reassign too much.
Every time reassign is called, would the old B die, or would it stay in memory until the instance of A is destroyed?
If it does stay in memory until A is destroyed, would this be to proper implementation?
1 2 3 4 5 6 7 8 9 10 11 12 13
class A
{
public :
void reassign();
private :
B* bPointer;
}
void A::reassign()
{
delete bPointer;
bPointer = new B();
}
Jan 15, 2012 at 9:29am UTC
If you do as in the first snippet, newB dies on line 13. All local variables die at the end of their scope. That is, bPointer will always point to invalid memory.
The second snippet is correct.
Jan 15, 2012 at 12:32pm UTC
Oh that's right, I didn't notice it.
Thanks.
Topic archived. No new replies allowed.