简体   繁体   English

当对象包含在c ++中的另一个对象中时,为什么复制构造函数被调用两次?

[英]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;
    }
};

wandbox example 魔盒示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么时候在c ++中调用了副本构造函数,当我将一个对象分配给另一个对象时不调用它吗? - When is a copy constructor called in c++, is not it called when I assign a object to another object? 为什么在实例化 object 时调用构造函数两次 - Why a constructor is called twice when an object is instantiated 当从 function 返回 object 时,会调用 C++ 中的复制构造函数? - Copy Constructor in C++ is called when object is returned from a function? 当我只返回对象c ++的引用时,为什么调用复制构造函数 - Why the copy constructor called, when I return just a reference of the object c++ 为什么我的 C++ 程序的复制构造函数被调用两次? - Why is my C++ program's copy constructor called twice? 类对象的C ++参考返回-为什么不调用复制构造函数? - C++ reference return of class object-why copy constructor not called? 为什么复制构造函数被调用,即使我实际上是在C ++中复制到已经创建的对象? - why copy constructor is getting called even though I am actually copying to already created object in C++? c ++为什么这个例子中的构造函数被调用了两次? - c++ why is constructor in this example called twice? 为什么在C ++中构造函数被两次调用? - Why is the constructor called twice in C++? 为什么在传递临时对象时未调用复制构造函数 - Why copy constructor is not called when pass temporary object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM