简体   繁体   English

为什么不调用移动构造函数? (默认情况下只有构造函数,没有别的)

[英]Why the move-constructor is not called ? (only the constuctor by default, and nothing else)

Could you explain me why, in the following, code,你能解释我为什么在下面的代码中,

#include <iostream>
#include <variant>
#include <string>



class MySecondType {
public:
    MySecondType() { std::cout << "Constructeur par défaut de MySecondType\n"; }
    MySecondType(const MySecondType&) // Constructeur par copie
    {std::cout<< "Constructeur par copie de MySecondType\n";}
    MySecondType(MySecondType&&) noexcept//Constructeur par déplacement 
    {
        std::cout << "COnstructeur par déplacement de MySecondType\n";
    }


    MySecondType& operator=(MySecondType&&) noexcept
    {
        std::cout << "Opérateur d'affection par déplacement\n";
        return *this;
    }

    MySecondType& operator=(MySecondType&) 
    {
        std::cout << "Opérateur d'affection par copie\n";
        return *this;
    }



    ~MySecondType() {
        std::cout << "Destructeur de MySecondType\n";
    }

};


int main() {

    MySecondType e;
    e= MySecondType() ;
return 0;
}

I have the result I wait, with :我有我等待的结果:

MySecondType e;
e= MySecondType() ;

BUT I don't have it , if I do :但我没有它,如果我这样做:

MySecondType e = MySecondType() ;

I expected that the line :我预计该行:

MySecondType e = MySecondType() ;

would call the move constructor(after the default constructor), but it does not call it.会调用移动构造函数(在默认构造函数之后),但它不会调用它。 It only creates an object with the default constructor , and that's nothing else.它只创建一个带有默认构造函数的对象,仅此而已。

Can you explain me why ?你能解释一下为什么吗?

Thank you谢谢

I'm asuming you actually do what @Jacob hinted at, ie MySecondType e = MySecondType();我假设你实际上做了@Jacob 暗示的事情,即MySecondType e = MySecondType(); . .

If so, then the compiler is eliding the copy/move constructor.如果是这样,那么编译器将省略复制/移动构造函数。 It sees that you are creating a temporary object and right after assigning it to a variable.它看到您正在创建一个临时对象,并在将其分配给变量后立即创建。 So instead of doing that, which would be inefficient, it skips the copy/move step and directly constructs the object at its final destination.因此,与其这样做,效率低下,不如跳过复制/移动步骤,直接在最终目的地构造对象。

AFAIK, this is an optional optimization pre-C++17. AFAIK,这是 C++17 之前的可选优化。 Starting in C++17 it's mandatory.从 C++17 开始,它是强制性的。

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

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