Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invoke the move constructor?

In the code show below, how do I assign rvalue to an object A in function main?

#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.

like image 214
codekiddy Avatar asked Jan 05 '12 09:01

codekiddy


1 Answers

Any named instance is l-value.

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)); 
}
like image 62
alexm Avatar answered Oct 04 '22 18:10

alexm