vendredi 5 juin 2015

std::forward and copy constructor

I have started leaning C++ recently. And I have a question on std::forward with lvalue reference and rvalue reference. In my understanding, The Func(mc) in the following code suppose to call Func(T& t) because of template parameter deduction rule. And copy constructor of MyClass should be called inside the function with a message, "copy constructor". However I cannot get it when I run the program. I checked that std::forwad with rvalue reference and copy constructor is working well in other lines. Please help me to understand what happen in the code. If I make easy mistake or misunderstanding, I am sorry for taking your time. Thank you very much.

class MyClass {
public:
    MyClass() { printf("constructor.\n"); };
    MyClass(MyClass&) { printf("copy constructor.\n"); };
    MyClass(const MyClass&) { printf("const copy constructor.\n"); };
    MyClass(MyClass&&) { printf("move constructor.\n"); };
    int val = 3;
};

template <typename T>
void Func(T&& t) {
    T new_t_(std::forward<T>(t));
    new_t_.val *= 2;
};

main() {
    MyClass mc;
    Func(mc);  // lvalue <- Func(T&)
    Func(MyClass());  // rsvalue <- Func(T&&)
    printf("mc.val=%d\n", mc.val); // this is for check

    MyClass mc2(mc);  // this is for check of copy constructor
}

Output when I run program is following,

constructor.
constructor.
move constructor.
mc.val=6
copy constructor.

I think it should have "copy constructor" between the first and the second "constructor" messages.

Thank you very much again.

Aucun commentaire:

Enregistrer un commentaire