简体   繁体   English

为什么在 c++11 中调用了复制构造函数但不移动构造函数?

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

This is the C++ test I do.这是我做的 C++ 测试。 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;参数名为lv但您在 function 中使用lr

  2. The argument lv is a reference to a constant MyTest object, it can't be "moved" from;参数lv是对常量MyTest object 的引用,它不能被“移动”;

  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.它通过右值初始化创建一个临时的 object。 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.但是由于不再使用 object,编译器可以自由地对其进行优化,从而使赋值运算符的主体为空。

    If you look at the generated code you will most likely see the object creation missing.如果您查看生成的代码,您很可能会看到 object 创建丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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