是否有正当理由不从复制赋值运算符返回* this?

时间:2015-05-20 21:34:59

标签: c++ copy-assignment

foo成为带有复制赋值运算符的结构或类:

struct foo {
    foo &operator=(const foo &);  // or with some other return type?
};

是否有明智的理由从*this返回operator=()以外的任何内容?将它用于与任务无关的事情并不合格。

2 个答案:

答案 0 :(得分:9)

标准中的示例是std::atomic。它返回指定的值。如果它返回了引用,那么通读它可能会产生不同的结果。

答案 1 :(得分:0)

如果您想阻止分配链接。

有时防止像这样的表达式很好:

x = y = z = a = b = c = d = foo{15};

所以你让赋值运算符返回void。

struct foo {
    void operator=(const foo &);
};

对于某些类型的链接没有意义。但是你必须根据具体情况来看待它。