移动ctor什么时候被调用?

The*_* do 1 c++ constructor c++11

鉴于课程:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后在主要:

int main(int argc, char* argv[])
{
    C c;
    C d = c;
    C e;
    e = c;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如您将从输出中看到的那样,复制ctor的"常规"版本operator=被调用但不是那些带有rvalue args的版本.所以我想问一下在什么情况下移动ctor并被operator=(C&&)调用?

Ant*_*ams 7

当右手边是一个临时的,或者一些已经显式转换为移动构造函数将被调用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
Run Code Online (Sandbox Code Playgroud)