C++11 应该是C++;11移动和复制赋值运算符返回常量?
C++11移动和复制赋值运算符是否应返回常量 示例代码:C++11 应该是C++;11移动和复制赋值运算符返回常量?,c++11,C++11,C++11移动和复制赋值运算符是否应返回常量 示例代码: const my_class& operator=(const my_class& other) { // Copy the data my_class tmp(other); *this = std::move(tmp); return *this; } const my_class& operator=(my_class&& other) { //
const my_class& operator=(const my_class& other)
{
// Copy the data
my_class tmp(other);
*this = std::move(tmp);
return *this;
}
const my_class& operator=(my_class&& other)
{
// Steal the data
std::swap(my_data_length, other.my_data_length);
std::swap(my_data, other.my_data);
return *this;
}
为清楚起见:
class my_class
{
protected:
double *my_data;
uint64_t my_data_length;
}
注意返回类型上的const
。我通常会不假思索地提出这个问题,但这真的有必要吗?返回const
会阻止您做什么?(这里举个例子会很有帮助。)
注:给出了一个示例,但随后将其删除。有人能评论一下吗<代码>(a=b)。非常量成员函数()代码>不,它们绝对不应该返回对const的引用。典型的声明是:
my_class& operator=(const my_class& other)
my_class& operator=(my_class&& other)
根据CPPPreference:
为复制和移动分配返回T&
是满足copyassiable
和MoveAssignable
概念的要求。简短回答:否
赋值运算符和诸如+=
e.t.c.之类的运算符应始终返回对类的引用,以便可以再次将其赋值给:
如果它返回const
,则不能执行以下操作,因为返回对象是不可变的
std::string str = "Hello";
(str = "Hello World") += "!";//assign value to hello world then append !
返回
const&
仍然允许您执行声明的const
函数,但不会修改容器,例如=
,+=
,交换
,e.t.c.返回值可用于链分配。所以常量返回将阻止这样的系统:(a=b)=c
。Asa=b
返回一个常量对象。a=b=c
表示a=(b=c)
,它仍然有效。当=
返回const
时,只有(a=b)=c
不起作用。它们从右到左分组(a=(b=c))
,因此它不是point@hvd代码(a=b)=c实际上会做什么?把b分配给a,然后呢?把c赋值给a?我错了。改变了分组。但在这种情况下这真的重要吗?因为如果这个代码把b分配给a,然后把c分配给a,那么这本质上等同于把c分配给a,而b从来没有出现过。。。那么在这种情况下,它是否编译真的很重要,因为您肯定永远不会想执行(a=b)=c
?不过,这仍然是一个有趣的例子。