【问题标题】:How (or why) the copy constructor is called?如何(或为什么)调用复制构造函数?
【发布时间】:2023-02-03 14:13:27
【问题描述】:
#include <iostream>

using namespace std;

struct Car
{
    int size = 4;
    int* tires = nullptr;

    Car()
    {
        cout << "ctor" << endl;
        tires = new int[size];
    }

    Car(const Car& car)
    {
        cout << "copy ctor" << endl;
        tires = new int[size];
        memcpy(tires, car.tires, size*sizeof(int));
    }

    Car& operator= (Car& car)
    {
        cout << "copy assignment operator" << endl;
        tires = new int[size];
        memcpy(tires, car.tires, size*sizeof(int));
        return *this;
    }

     ~Car()
    {
        cout << "dtor" << endl;
        delete tires;
    }
};

int main()
{
    cout  << "starting..." << endl;

    Car car1;
    car1.tires[0] = 2;

//    Car car2(car1); // #1
    Car car2 = car1; // #2 I was expecting the assingment operator to be called here

    cout << car1.tires[0] << " " << car2.tires[0] << endl;

    return 0;
}

我明白为什么在#1 调用复制构造函数,但它最终如何在#2 被调用?

【问题讨论】:

  • 赋值是在创建变量后赋值给它:Car car2; car2 = car1;

标签: c++ constructor


【解决方案1】:

Car car2 = car1;不是赋值,是initialization,具体是Copy Initialization。编译器将其视为您编写了Car car2(car1);。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 2021-02-18
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2011-04-18
    相关资源
    最近更新 更多