I have structure aa and I’m trying to run such code:
aa * b = new aa;
aa * c = new aa;
c=b;
delete (b);
c.useSomeFunction
Can I use the object pointed to by c after destruction of b?
The same question in case of:
aa * b = new aa;
aa * c ;
c=b;
delete (b);
c.useSomeFunction
The title of the question is misleading, because you don’t use an
operator=()in your code. You only assign pointers which are built-in types.As pointed out before:
In your first example, the pointer assignment yields a memory leak, as the object
(*c)can no longer be deleted. Also you cannot call a function of(*b)(even if pointed to bycafter deleting object(*b).In your second example you don’t get the memory leak. Note that in production code you should initialise every pointer with
nullptr. Also here you cannot access a function of(*b)after deleting the object.the call to the function must be
c->useSomeFunction()in order to by syntactically correct.What you probably want (and is suggested by the title) is to create a new object and assign the content of the old one to it. Something like: