给定的类:
class C
{
public:
C()
{
cout << "Dflt ctor.";
}
C(C& obj)
{
cout << "Copy ctor.";
}
C(C&& obj)
{
cout << "Move ctor.";
}
C& operator=(C& obj)
{
cout << "operator=";
return obj;
}
C& operator=(C&& obj)
{
cout << "Move operator=";
return obj;
}
};
然后在主要部分:
int main(int argc, char* argv[])
{
C c;
C d = c;
C e;
e = c;
return 0;
}
正如您将从输出中看到的那样,调用了复制构造函数和 operator=
的“常规”版本,但没有调用具有右值参数的那些。所以想问一下move ctor和operator=(C&&)
在什么情况下会被调用?
最佳答案
移动构造函数将在右侧是临时的或已显式转换为 C&&
的内容时被调用。使用 static_cast<C&&>
或 std::move
.
C c;
C d(std::move(c)); // move constructor
C e(static_cast<C&&>(c)); // move constructor
C f;
f=std::move(c); // move assignment
f=static_cast<C&&>(c); // move assignment
C g((C())); // move construct from temporary (extra parens needed for parsing)
f=C(); // move assign from temporary
关于c++ - 什么时候调用 move ctor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413308/