Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is move-constructor not called? [duplicate]

I have the following piece of code:

#include <iostream>

struct T {
    int a;

    T() = default;

    T(T& other) {
        std::cout << "copy &\n";
    }

    T(T&& other) {
        std::cout << "move &&\n";
    }
};

void foo(T&& x) {
    T y(x); // why is copy ctor called??????
}

int main() {
    T x;
    foo(std::move(x));

    return 0;
}

I don't understand why copy constructor is preferred over move constructor even though foo() accepts rvalue-reference.

like image 845
mouse_00 Avatar asked Mar 02 '23 09:03

mouse_00


1 Answers

x is an lvalue itself, even its type is rvalue-reference. Value category and type are two independent properties.

Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;

You need to use std::move to convert it to rvalue, just same as using std::move on x in main().

void foo(T&& x)
{
    T y(std::move(x));
}
like image 70
songyuanyao Avatar answered Mar 12 '23 04:03

songyuanyao