简体   繁体   中英

why copy constructor called but not move constructor in c++11?

This is the C++ test I do. I thought move constructor would be called, but it's not. neither the two cases will call move constructure.

class MyTest
{
public:
    MyTest() {}
    ~MyTest() {}
    MyTest(const MyTest& lv) {}     // be called actually 
    MyTest(MyTest&& rv) {}          // not be called actually, but i thought would
    void operator=(const MyTest& lv) {
        MyTest(std::move(lr));      // i thought the move constructor would be called here
    }
};
int main()
{
    // case1:
    MyTest m1;
    MyTest m2 = m1;

    // case2:
    MyTest m3;
    MyTest m4;
    m4 = m3;       // move constructure will not be called either.
    return 0;
}

Your copy assignment operator

void operator=(const MyTest& lv) {
    MyTest(std::move(lr));
}

have three problems:

  1. The argument is named lv but you use lr inside the function;

  2. The argument lv is a reference to a constant MyTest object, it can't be "moved" from;

  3. And the statement

    MyTest(std::move(lv)); // Corrected the variable name

    doesn't make much sense on its own.

    It creates a temporary object by rvalue initialization. But since the object isn't used any more the compiler is free to optimize it away making the body of the assignment operator empty.

    If you look at the generated code you will most likely see the object creation missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM