分配运算符的返回类型

Return type for the assignment operator

本文关键字:返回类型 运算符 分配      更新时间:2023-10-16

用其类名称定义的操作员有什么区别:

class RefObj {
public:
    RefObj &operator=(const RefObj &) { return *this; }
private:
    int m_Counter = 0;
};

和一个带有void的操作员:

template<class T> class SmartPtr {
public:
    void operator=(T* pointer) { m_SmartPtr = pointer; }
private:
    T* m_SmartPtr;
}

我什么时候应该使用第一个,什么时候应该使用第二个?

第一个版本允许在一行中对返回对象进行进一步的操作,如

中的
(refobj = a).do_something();

当您不返回对对象的引用时,这是不可能的。您可能会认为这很愚蠢,但请考虑输出操作员。

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

鉴于返回参考真的很便宜,我建议始终返回一个。这将为您节省搜索奇怪的错误的痛苦,否则完美的理智语法会破坏您的代码。