What is the difference between returning *this or the given argument in implementation of operator= in C++? Is using one of them better or more useful? if yes, why?
class Object {
public:
Object operator=(Object Obj) {
return *this;
}
}
vs.
class Object {
public:
Object operator=(Object Obj) {
return Obj;
}
}
Pete Fordham
2,34316 silver badges25 bronze badges
-
1You should be returning a reference to the current object, not a brand new object.PaulMcKenzie– PaulMcKenzie2020年05月10日 15:52:14 +00:00Commented May 10, 2020 at 15:52
-
Does this answer your question? What is The Rule of Three?Spencer– Spencer2020年05月10日 15:54:22 +00:00Commented May 10, 2020 at 15:54
1 Answer 1
X& operator=( X const& ) { return *this; } matches the semantics of = on an int. The other suggestions you gave do not. When in doubt match the semantics of int.
answered May 10, 2020 at 15:53
Yakk - Adam Nevraumont
280k31 gold badges367 silver badges585 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-cpp