Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ dynamic memory detail

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.

like image 596
Junier Avatar asked Nov 27 '22 22:11

Junier


2 Answers

No.

You only need to free memory you allocate (i.e. via new or memalloc).

like image 104
Burkhard Avatar answered Nov 29 '22 13:11

Burkhard


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.

like image 28
Joakim Elofsson Avatar answered Nov 29 '22 12:11

Joakim Elofsson