C++ dynamic memory detail

c++, dynamic, free, memory, memory-management

Solution

No,

Both `s1` and `s2` will get destructed when out of scope.

`s1.substr()` will create a temporary object that you don't have to think of.

Problem

I'm a C and Java programmer, so memory allocation and OOP aren't anything new to me. But, I'm not sure about how exactly to avoid memory leaks with C++ implementation of objects. Namely: ``` string s1("0123456789"); string s2 = s1.substr(0,3); ``` `s2` now has a new string object, so it must be freed via: ``` delete &s2; ``` Right? Moreover, am I correct to assume that I'll have to delete the address for any (new) object returned by a function, regardless of the return type not being a pointer or reference? It just seems weird that an object living on the heap wouldn't be returned as a pointer when it must be freed.

Original source