[英]why the copy constructor is called twice when the object is contained in another object in c++?
//V4.cpp
#include <iostream>
using namespace std;
class V3 {
private:
double x, y, z;
public:
V3(double a, double b, double c): x(a), y(b), z(c) {
cout << "V3(double, double, double)" << endl;
}
V3(const V3 &a): x(a.x), y(a.y), z(a.z) {
cout << "V3(const V3 &)" << endl;
}
};
class V4 {
private:
V3 xyz;
double time;
public:
V4(V3 a, double t): xyz(a), time(t) {
cout << "V4(V3, double)" << endl;
}
};
int main(void)
{
V3 xyz(1.0, 2.0, 3.0);
double t(4.0);
V4 xyzt(xyz, t);
return 0;
}
the class V4 contains another class V3, and the object of V4 is initialized by an exist object of V3, so the V4's constructor will call V3's copy constructor, and I think the copy constructor will be called once, but the result shows it's called tiwce, why is it? V4类包含另一个V3类,并且V4的对象由V3的存在对象初始化,因此V4的构造函数将调用V3的copy构造函数,我认为copy构造函数将被调用一次,但是结果表明它被称为tiwce , 为什么?
compile the code: 编译代码:
g++ V4.cpp -o V4 -Wall
and run: 并运行:
./V4
and the result: 结果:
V3(double, double, double)
V3(const V3 &)
V3(const V3 &)
V4(V3, double)
so look the result, why the V3 copy constructor is called twice? 那么看看结果,为什么V3复制构造函数被调用两次? my OS is Lubuntu16.04,and g++ is 5.4.0
我的操作系统是Lubuntu16.04,而g ++是5.4.0
You're taking V3 a
by value in V4
's constructor, resulting in an additional unnecessary copy. 您正在
V4
的构造函数中按值使用V3 a
,从而导致额外的不必要副本。 You should take it by const&
: 您应该使用
const&
:
class V4 {
private:
V3 xyz;
double time;
public:
V4(const V3& a, double t): xyz(a), time(t) {
// ^^^^^^^^^^^
cout << "V4(V3, double)" << endl;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.