简体   繁体   中英

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?

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? my OS is Lubuntu16.04,and g++ is 5.4.0

You're taking V3 a by value in V4 's constructor, resulting in an additional unnecessary copy. You should take it by const& :

class V4 {
private:
    V3 xyz;
    double time;
public:
    V4(const V3& a, double t): xyz(a), time(t) {
//     ^^^^^^^^^^^
        cout << "V4(V3, double)" << endl;
    }
};

wandbox example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM