rvalue作为构造对象的初始化器

Car*_*ung 5 c++

我是编程新手.对不起,我的英语不好.我试图使用rvalue作为初始对象的初始化器.因此,根据代码,它将打印出使用的构造函数和赋值运算符.但结果是对象"what2"和"what3",那些不打印任何东西.这是代码:

#include <iostream>
using namespace std;
class X{
public:
    int x;
    X()= default;
    X(int num):x{num}{}
    X(const X& y){
        x = y.x;
        std::cout << "copy constructor" << std::endl;
        std::cout << x << std::endl;

    }
    X& operator=(const X& d){
        x = d.x;
        std::cout << "copy assignment" << std::endl;
        return *this;
    }
    X(X&& y){
        x = y.x;
        std::cout << "move constructor" << std::endl;
    }
    X& operator=(X&& b){
        x = b.x;
        std::cout << "move assignment" << std::endl;
        return *this;
    }
};

X operator +(const X& a,const X& b){
    X tmp{};
    tmp.x = a.x +b.x;
    return tmp;
}

int main(int argc, const char * argv[]) {
    X a{7} , b{11};
    X what1;
    cout << "---------------" << endl;
    what1 = a+b;
    cout << "---------------" << endl;
    X what2{a+b};
    cout << "---------------" << endl;
    X what3 = a+b;
    cout << "---------------" << endl;
    std::cout << what1.x << std::endl;
    std::cout << what2.x << std:: endl;
    std::cout <<what3.x << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

---------------
move assignment
---------------
---------------
---------------
18
18
18
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)

只有"what1"正确使用赋值.那么,我如何使用rvalue初始化一个对象?并使用operator =来初始化一个对象?非常感谢你.

Tar*_*ama 5

您的代码可能会导致使用移动操作,但您的编译器已选择省略这些移动并operator+直接在调用站点分配返回值。如果您在编译器(-fno-elide-constructors在 GCC 或 Clang 中)中禁用复制省略,您会看到这种情况发生。

您的移动构造函数和赋值运算符将在不允许复制省略的上下文中成功使用,例如:

X what2 { std::move(what1) }; //can't elide copy, move constructor used
Run Code Online (Sandbox Code Playgroud)