How std::move can work with copy-constructor that takes non-const reference?

82 Views Asked by At

I was reading about std::move. Based on quite few materials, I concluded that std::move is just a function that converts its argument type to the rvalue-reference.

I also read that, rvalue-references can be used with the functions that take their arguments as const-references. This is meaningful because the contents of the objects guaranteed to be not changed.

To verify these ideas, I made a very simple experiment with a class located below.

I have created an object t1 and used std::move to convert it to rvalue-reference and tried to create another object t2 with calling copy-constructor.

The mysterious part is that even if I don't provide move-constructor, it works with the copy-constructor which I intentially defined its parameter as non-const reference.

However, if std::move converts type of t1 to rvalue-reference, how compiler can bind it to the lvalue-reference?

Btw, I am using "Microsoft (R) Microsoft Visual Studio 2012 Version 11.0.50727.1".

Could you please explain what I am missing here?

Thank you very much.

#include <iostream>
#include <algorithm>

using namespace std;

class Trace {
    public:
        Trace() {
        }

        // @1
        Trace(Trace& t) {
            cout << "trace::trace(&)" << endl;
        }

        // @2
        Trace(Trace&& t) {
            cout << "trace::trace(&&)" << endl;
        }
};

int main(int argc, const char *argv[])
{
    Trace t1;

    // Calls @2 if it exists, otherwise calls @1 
    Trace t2(std::move(t1));
    return 0;
}
0

There are 0 best solutions below