为什么没有一个复制构造函数被调用 [duplicate]

why is none of the copy constructors being called [duplicate]

提问人:Lucy 提问时间:12/4/2022 更新时间:12/4/2022 访问量:40

问:

#include <iostream>

using namespace std;

struct foo{
    int x;
    double y;
    double z;

    foo(int x_,double y_,double z_)
    {
        x = x_;
        y = y_;
        z = z_;
    }
    foo(const foo& f){
        cout<<"foo copy for const ref called"<<endl;
        x = f.x;
        y = f.y;
        srand((unsigned ) time(nullptr));
        int z_ = rand();
        z = z_;
        cout<<f.x<<endl;
    }
    foo(foo&& f) {
        cout<<"foo copy for right ref called"<<endl;
        x = f.x;
        y = f.y;
        srand((unsigned ) time(nullptr));
        int z_ = rand();
        z = z_;
        cout<<f.x<<endl;
    }
};

int main()
{
    srand((unsigned ) time(nullptr));
    int rand_ = rand();
    foo f_(foo(rand_, 2, 3));
    cout<<f_.x<<' '<<f_.y<<' '<<f_.z<<endl;
}

我在 gcc 中运行上述代码,并得到以下输出:

21862 2 3

我期望比将要被调用,但出乎我的意料,没有一个复制构造函数被调用,并且被设置为,我希望它是一个随机值。 为什么没有调用任何复制构造函数?foo(foo&& f)f_.z3

C++ GCC 编译器优化 复制构造函数

评论

1赞 UnholySheep 12/4/2022
复制/移动省略:en.cppreference.com/w/cpp/language/copy_elision
1赞 Eljay 12/4/2022
C++ 要求(从 C++ 17 开始)复制省略。如果复制构造函数有副作用,则可能不会发生这些副作用(如 )。C++期望构造函数执行特定的语义(而不是做副作用;许多程序员会忘记这一点 - 包括我自己不时),这需要允许复制省略cout
0赞 user12002570 12/4/2022
请参阅 dupe1、dupe2dupe3

答: 暂无答案