开发者

Confusing between object in Heap and Stack memory

开发者 https://www.devze.com 2023-03-06 22:34 出处:网络
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

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 obj开发者_如何转开发ect 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?


 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+ )


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.


In your example, Sterling is returned as a pass-by-value object -- it is stored on the stack (or registers, whichever way the compiler chooses to store it).

0

精彩评论

暂无评论...
验证码 换一张
取 消