Reputation: 24771
Will creating this new object, v
, result in an entirely new object or simply the same object space referenced by *this
?
Vector2 v = *this;
I would not expect it is actually creating a new object, but I'm seeing this code in a sample app that then manipulates this new object even though this code is in a class function that is set as const
. Thus I would expect that this object,v
, is in fact entirely a separate memory space than *this
.
Upvotes: 2
Views: 101
Reputation: 11038
Assuming that you are inside a Vector2
method, this operator =
you are using is called copy assignment for a reason. Now, whether it does a deep copy, a shallow copy (copies pointers, but not the objects pointed by them) or whatever is down to the actual implementation of the operator.
Upvotes: 1
Reputation: 258618
It's creating a new object, yes - but by initialization, not assignment.
You can however bypass that by using references, Vector2& v = *this;
, in which case v
is an alias for *this
(or const Vector& v = *this
, if the method is const
).
The reasons for this is exactly the one you stated - since the method in which this happens is const
, there's no way to mutate *this
- so you need a non-const
copy of it.
Upvotes: 5