c++ - 什么时候调用 move ctor?

标签 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;
    }
};

然后在主要部分:

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/

相关文章:

c++ - 使用 ostream 统一输出带符号的 0.0

c++ - 这个拷贝构造函数做的是深拷贝还是浅拷贝?

c++ - 标准是否指定哪些函数被声明为内联?

c++ - 在 C++ 中既不调用 Copy 也不调用 Move 构造函数

c++ - 是否有任何类型特征控制成员类型(不是成员变量)

c++ - foo({0, 0}) : Is this using initializer lists?

c++ - 在 Qt 虚拟键盘上实现 Backspace 和 Enter 键

c++ - 如何识别从 iBrokers API 接收到的 HistoricalData 的类型(whatToShow)

c++ - 为什么 boost 服务器类抛出运行时错误

asp.net - 在 ASPX 页面中使用构造函数(无代码隐藏)