Reputation: 1887
What is the difference between
What is written in the textbook:
MyClass& Myclass::operator++() {
do something
return *this;
}
and
MyClass Myclass::operator++() {
do something
return *this;
}
*
means "value pointed by" ....
is it that the second example will return a copy of the object pointed by this (a copy of *this) while the first example will return *this itself?
if this is the case then what difference does it make? to improve execution time?
Upvotes: 0
Views: 63
Reputation: 208323
As you already mention in the answer, the first one returns a reference and the second one is making a copy. The main difference is that the semantics are completely different, consider:
const auto & r = ++a;
++a;
assert(a == r); // true/false depending on what is returned
In the particular case of prefix operator++
, the correct semantics (the one that most users will expect) is yielding a reference. Doing any other thing will cause confusion and probably end up being the source of bugs in the source code.
In a more general question, if the function had no predefined expected semantics, the difference would still be the same regarding usage. The will be a higher cost if you copy (for those types for which the copy might be expensive), but if you need reference semantics you will need to yield a reference, and if you need copy semantics you will need to return by value no matter how cheap/expensive that is.
Note that regarding the cost, it might be less than you expect, depending on what you are actually doing. If the caller is going to use the return to initialize a new object, the cost is probably going to be the same as RVO will kick in and remove the unnecessary extra copy.
Upvotes: 0
Reputation: 3819
the difference between the two is that
in case 1
you are returning a reference ie you are returning a constant pointer to the object.
In case 2
you are creating a new object and returning the object
Lets dig a little deeper to understand things better
In case 1
since you are returning the pointer to the existing object any changes you make with affect the original object
In case 2
since its a copy there is no impact on the original object
In terms of speed and memory
In case of 1
since you returning the address of an existing object there is no or little overhead
In case 2
you are creating a new copy ...so constructor of the object would be invoked and hence there is overhead in terms of memory and time taken
Upvotes: 1
Reputation: 79441
The second version will copy the MyClass
object (i.e. *this
). The first will return only a reference to it.
It's not that either one is "correct" - it's that they have different meanings. Sometimes you want to clone an object so that you have two (possibly) independent copies. Sometimes you want to share a single object.
Upvotes: 0