`void operator=(T&&)` 和 `T& operator=(T&&)` 有什么区别?
What is the difference between `void operator=(T&&)` and `T& operator=(T&&)`?
class base
{
public:
base(const base&) = delete;
base()
{
cout << "construct" << endl;
}
~base()
{
cout << "destruct" << endl;
}
int a;
int b;
/* The difference explanation I desired is here */
void operator=(base&& other)
// base& operator=(base&& other) // this needs to collaborate with "return *this"
{
this->a = other.a;
this->b = other.b;
// return *this;
}
/* Not here */
base& operator=(base& other) = delete;
};
operator=(T&&)
两个版本有什么区别?他们似乎都对我有用。但是,作为class成员函数,本站推荐base& operator=(T&&)
版本。
在一种情况下,a=b=c
有效。另一方面,它没有。
就是这样。
传统上,a=b=c
执行 b=c
,然后将结果分配给 a
。如果你的 operator=
returns void
,它反而编译失败。
class base
{
public:
base(const base&) = delete;
base()
{
cout << "construct" << endl;
}
~base()
{
cout << "destruct" << endl;
}
int a;
int b;
/* The difference explanation I desired is here */
void operator=(base&& other)
// base& operator=(base&& other) // this needs to collaborate with "return *this"
{
this->a = other.a;
this->b = other.b;
// return *this;
}
/* Not here */
base& operator=(base& other) = delete;
};
operator=(T&&)
两个版本有什么区别?他们似乎都对我有用。但是,作为class成员函数,本站推荐base& operator=(T&&)
版本。
在一种情况下,a=b=c
有效。另一方面,它没有。
就是这样。
传统上,a=b=c
执行 b=c
,然后将结果分配给 a
。如果你的 operator=
returns void
,它反而编译失败。