C++:右值引用构造函数和复制省略

C++: rvalue reference constructor and copy-elision

本文关键字:复制省 构造函数 引用 C++      更新时间:2023-10-16

我正在尝试理解右值引用构造函数和赋值运算符。 我创建了以下源代码,它应该调用rvalue 引用构造函数,但它没有发生。 我怀疑是复制消除优化是原因。 有谁知道这是不是原因? 另外,如果复制省略是原因,那么代码中右值引用的意义何在?

#include <iostream>
#include <vector>
using namespace std;
class X {
public:
X() : v{new vector<int>(0)} { }
X(const X&);
X(X&&);
X& operator=(const X& rhs);
X& operator=(X&& rhs);
private:
vector<int> *v;
};
X::X(const X& a)
{
cout << "copy constructor" << endl;
for (auto p : *(a.v))
v->push_back(p);
}
X::X(X&& a) : v{a.v}
{
cout << "rval ref constructor" << endl;
a.v = nullptr;
}
X& X::operator=(const X& rhs)
{
cout << "assignment operator" << endl;
delete v;
v = new vector<int>();
for (auto p : *(rhs.v))
v->push_back(p);
return *this;
}
X& X::operator=(X&& rhs)
{
cout << "rval ref assignment op" << endl;
swap(v, rhs.v);
return *this;
}
X f0()
{
return X(); // copy-elision no move called
// return move(X());
}
int main(int argc, char *argv[])
{
X x1(f0());
return 0;
}

将以下内容添加到 main((:

X x2(std::move(x1));

这手动指示对象 X1 可以从中移动以解决复制省略问题。 并不总是调用 copy-elision,因此在某些情况下可能需要 rvalue 引用构造函数和赋值运算符。