gpt4 book ai didi

c++ - 构造函数和拷贝构造函数

转载 作者:行者123 更新时间:2023-11-28 00:40:19 26 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

class t{
private:
int * arr;

public:
t() { arr=new int[1]; arr[0]=1;}
t(int x) {arr=new int[1]; arr[0]=x;}
t(const t &);
~t() {cout<<arr[0]<<" de"<<endl; delete [] arr;}
t & operator=(const t & t1){arr[0]=t1.arr[0];return *this;}
void print(){cout<<arr[0]<<endl;}

};
t::t(const t & t1) {arr=new int[1];arr[0]=t1.arr[0];}

int main(){

t b=5;
cout<<"hello"<<endl;
b.print();
b=3;
b.print();
return 0;
}

为什么结果是

hello
5
3 de
3
3 de ?

为什么“t b=5;”不会调用析构函数? “t b=5”是如何工作的?它是否首先使用构造函数“t(int x)”创建一个临时对象(t 类),然后使用复制构造函数“t(const t &)”创建 b?如果是这样,为什么它不调用临时对象的析构函数?

最佳答案

why "t b=5;" will not call the destructor?

当你这样做时:

t b=5;

你得到 copy initialization .从语义上讲,调用隐式转换构造函数t(int),然后调用复制构造函数t(const t&)实例化b。但是,允许编译器 elide the copy ,这就是您的情况。该对象是就地构造的,不需要复制构造。这就是为什么您看不到析构函数调用的原因。但是您的类仍然需要一个复制构造函数来编译该代码:复制省略是可选的,某些代码是否编译不应取决于编译器是否执行省略。

如果你说

t b(5);

然后将直接初始化,没有复制省略,并且只有一个构造函数调用。您的类不需要复制构造函数来编译此代码。

关于c++ - 构造函数和拷贝构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19216972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com