Yes, I'm one of those fellows that is learning C++ coming from Java, being spoiled with an automatic garbage collector. There's a particular situation where I'm wondering whether I'm leaking memory or not. Let's consider in C++:
bool *test = new bool(false);
test = new bool(true);
delete test;
Am I leaking memory here? Or should I first call delete
before assigning a new value? Like this:
bool *test = new bool(false);
delete test;
test = new bool(true);
delete test;
My gut feeling tells me the first is right, as the pointer test
points at the same address in memory, and assigning a new value to its variable, will not change this address. Or does the new
operator allocate a different address in memory? Can anyone give me a clue, or did I get it wrong all together?
Yes you are leaking, and the c++ way to do it is:
bool test = false;
test = true;
// ta-da - no leak.
You could do the second approach - however you're likely to draw lots of frowning...
Yes, exactly, you have to delete
before you overwrite the address. Or better yet allocate on stack or use a smart pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With