Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing between object in Heap and Stack memory

Tags:

c++

A method;

        Sterling operator+(const Sterling& o) const {
           return Sterling(*this) += o;
         }

Does this line "Sterling(*this) += o" create a new Object in stack memory? If true, how can it return an object in the stack to outside the method?

Can I do like this:

         Sterling operator+(const Sterling& o) const {
           return *this += o;
         }

because I think *this is an object so we don't need to create a new Object?

like image 480
Xitrum Avatar asked Jul 14 '26 00:07

Xitrum


2 Answers

 Sterling operator+(const Sterling& o) const {
     return Sterling(*this) += o;
 }

Creates object on the stack, but you don't actually return this object, you return a copy of it. This function does:

  • create a temp object
  • call operator+= of the temp object with o
  • return copy of the result - note the Sterling operator+(const Sterling& o) const - if it was Sterling& operator+(const Sterling& o) const ( *note the & * ), then this would be a problem )

Anyway, your compiler could optimize this and avoid copying of the local object, by using RVO


And the second question:

Sterling operator+(const Sterling& o) const {
   return *this += o;
}

This is different from the first one - the first case creates temp object and changes it, then returns it. If you do the second, this will change this and then return copy of it. But note, this object is changed!


So, the summary - both return the same result, but the second changes this. (his would be useful, if you want to overload operator+=, not operator+ )

like image 58
Kiril Kirov Avatar answered Jul 15 '26 13:07

Kiril Kirov


Here:

Sterling operator+(const Sterling& o) const {
   return Sterling(*this) += o;
}

a temporary (yes, new) object is created (on stack, or more strictly speaking, in automatic storage) and then the temporary object altered and its copy is returned from the function (in some implementation defined way).

Here:

Sterling operator+(const Sterling& o) const {
   return *this += o;
}

the current object (the one on which the method is called) is altered, then its copy is returned from the function.

So the major difference is whether the current object is altered or a temporary one. In both cases the altered object is then copied and returned from the function.

like image 24
sharptooth Avatar answered Jul 15 '26 14:07

sharptooth