是否有正当理由不使用 return *this 来自复制赋值运算符?
Is there ever a valid reason to not return *this from copy assignment operator?
设 foo
为结构或 class 并带有复制赋值运算符:
struct foo {
foo &operator=(const foo &); // or with some other return type?
};
除了 operator=()
中的 *this
之外,是否有 合理的理由return?将它用于与分配无关的事情并不合理。
标准中的例子是std::atomic
。它 returns 分配的值。如果它返回引用,那么通读它可能会产生不同的结果。
如果你想防止赋值链接。
有时候防止这样的表达是很好的:
x = y = z = a = b = c = d = foo{15};
因此您使赋值运算符 return 无效。
struct foo {
void operator=(const foo &);
};
对于某些类型,链接没有意义。但是你必须根据具体情况来考虑。
设 foo
为结构或 class 并带有复制赋值运算符:
struct foo {
foo &operator=(const foo &); // or with some other return type?
};
除了 operator=()
中的 *this
之外,是否有 合理的理由return?将它用于与分配无关的事情并不合理。
标准中的例子是std::atomic
。它 returns 分配的值。如果它返回引用,那么通读它可能会产生不同的结果。
如果你想防止赋值链接。
有时候防止这样的表达是很好的:
x = y = z = a = b = c = d = foo{15};
因此您使赋值运算符 return 无效。
struct foo {
void operator=(const foo &);
};
对于某些类型,链接没有意义。但是你必须根据具体情况来考虑。