提问人:Lucy 提问时间:12/4/2022 更新时间:12/4/2022 访问量:40
为什么没有一个复制构造函数被调用 [duplicate]
why is none of the copy constructors being called [duplicate]
问:
#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_.z
3
答: 暂无答案
评论
cout