请问,能否用通俗易懂的语言解释一下什么是"将移动语义扩展到*this"?我指的是这个提案。我只想知道它是做什么的,以及为什么我们需要它。请注意,我理解什么是右值引用,这是移动语义的基础。但我无法理解这种扩展对右值引用有什么影响!
ref-qualifier特性(指示*this
的类型)允许您区分成员函数是否可以在rvalue或lvalue(或两者)上调用,并基于此重载函数。 第一个版本在非正式部分中提供了一些基本原理:
Prevent surprises:
struct S { S* operator &() &; // Selected for lvalues only S& operator=(S const&) &; // Selected for lvalues only }; int main() { S* p = &S(); // Error! S() = S(); // Error! }
Enable move semantics:
class X { std::vector<char> data_; public: // ... std::vector<char> const & data() const & { return data_; } std::vector<char> && data() && { return data_; } //should probably be std::move(data_) }; X f(); // ... X x; std::vector<char> a = x.data(); // copy std::vector<char> b = f().data(); // move
Foo operator+(Foo&& a, const Foo& b)
{
a += b;
return std::move(a);
}
Foo Foo::operator+(const Foo& b) && // note the double ampersand
{
*this += b;
return *this;
}
*this
,可以参考这里的讨论。