![](/img/trans.png)
[英]When is a copy constructor called in c++, is not it called when I assign a object to another object?
[英]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;
}
V4类包含另一个V3类,并且V4的对象由V3的存在对象初始化,因此V4的构造函数将调用V3的copy构造函数,我认为copy构造函数将被调用一次,但是结果表明它被称为tiwce , 为什么?
编译代码:
g++ V4.cpp -o V4 -Wall
并运行:
./V4
结果:
V3(double, double, double)
V3(const V3 &)
V3(const V3 &)
V4(V3, double)
那么看看结果,为什么V3复制构造函数被调用两次? 我的操作系统是Lubuntu16.04,而g ++是5.4.0
您正在V4
的构造函数中按值使用V3 a
,从而导致额外的不必要副本。 您应该使用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.