mercredi 24 novembre 2021

Why is move-constructor not called?

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.

Aucun commentaire:

Enregistrer un commentaire