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?
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:
operator+= of the temp object with oSterling 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.
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