简体   繁体   English

如何调用移动构造函数?

[英]How do I invoke the move constructor?

In the code show below, how do I assign rvalue to an object A in function main? 在下面的代码中,如何为函数main中的对象A分配rvalue?

#include <iostream>

using namespace std;

class A
{
    public:
        int* x;
        A(int arg) : x(new int(arg)) { cout << "ctor" << endl;}
        A(const A& RVal) { 
            x = new int(*RVal.x);
            cout << "copy ctor" << endl;
        }
        A(A&& RVal) { 
            this->x = new int(*RVal.x);
            cout << "move ctor" << endl;
        }
        ~A()
        {
            delete x;
        }
};

int main()
{
    A a(8);
    A b = a;
    A&& c = A(4); // it does not call move ctor? why?
    cin.ignore();
    return 0;
}

Thanks. 谢谢。

Any named instance is l-value. 任何命名的实例都是l值。

Examples of code with move constructor: 带有移动构造函数的代码示例:

void foo(A&& value) 
{
   A b(std::move(value)); //move ctr
}

int main()
{
    A c(5); // ctor
    A cc(std::move(c)); // move ctor
    foo(A(4)); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何避免转换运算符调用复制构造函数? - How do I avoid a conversion operator to invoke the copy constructor? 如何为成员变量调用非默认构造函数? - How do I invoke non-default constructor for a member variable? 如何只对move-constructor进行一次调用? - How do I make only a single call to the move-constructor? 如何强制调用移动构造函数,为什么要这样做? - How to force the call to move constructor and why should I do that? 如果我删除了复制构造函数,我是否没有隐式移动构造函数? - If I delete the copy constructor, do I get no implicit move constructor? 如何从类型列表中为每个继承的类型调用非默认构造函数? - How do I invoke a non-default constructor for each inherited type from a type list? 对对象使用右值时如何正确调用复制构造函数? - How do I invoke copy constructor appropriately while using rvalue for an object? 按值传递不会调用移动构造函数 - Passing by value doesn't invoke move constructor 为什么此函数不调用move构造函数? - Why does this function not invoke the move constructor? 如何使用移动语义从类构造函数重新分配资源? - How do I use move-semantics to reallocate resources from class constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM