Reputation: 503
What is the difference between an operator defined with its class name:
class RefObj {
public:
RefObj &operator=(const RefObj &) { return *this; }
private:
int m_Counter = 0;
};
and an operator with void:
template<class T> class SmartPtr {
public:
void operator=(T* pointer) { m_SmartPtr = pointer; }
private:
T* m_SmartPtr;
}
When should I use the first one and when should I use the second one?
Upvotes: 1
Views: 84
Reputation: 3589
The first version allows to do further operations on the returned object in one line as in
(refobj = a).do_something();
When you don't return a reference to the object, this is not possible. You may think this is silly, but think about output operators.
void operator<<(std::ostream &out, const Obj1 &obj1);
std::ostream& operator<<(std::ostream &out, const Obj2 &obj2);
Obj1 obj1;
Obj2 obj2;
std::cout << obj1 << '\t' << obj1 << std::endl; // compiler error
// ^^^^ '<<' can't operate on void
std::cout << obj2 << '\t' << obj2 << std::endl; // works!
// ^^^^ return type is std::ostream, '<<' work on that
Given that returning a reference is really cheap, I recommend to always return one. This will save you the pain of searching for strange bugs where otherwise perfectly sane syntax will break your code.
Upvotes: 2