![](/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.