我试图理解rvalue引用构造函数和赋值操作符。我创建了下面的源代码,它应该调用rvalue引用构造函数,但是它不会发生。我的怀疑是复制优化是原因。有人知道这是不是原因吗?另外,如果复制-省略是原因,那么代码中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;
}发布于 2020-06-06 22:35:58
在main()中添加以下内容:
X x2(std::move(x1));此手动指示可以将x1从对象移动到复制省略。复制-省略并不总是被调用,因此可能需要rvalue引用构造函数和赋值操作符。
https://stackoverflow.com/questions/62238613
复制相似问题