#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?如果是这种情况,为什么它不调用temp对象的描述器?
发布于 2013-10-07 12:42:42
为什么"t b=5;“不调用析构函数?
执行此操作时:
t b=5;你得到了copy initialization。从语义上讲,先调用隐式转换构造函数t(int),然后调用复制构造函数t(const t&)来实例化b。但是,编译器被允许执行elide the copy,这就是在您的例子中发生的事情。对象是就地构造的,不需要复制构造。这就是为什么你看不到析构函数调用的原因。但是您的类仍然需要一个复制构造函数来编译该代码:复制省略是可选的,一些代码是否编译不应该取决于编译器是否正在执行省略。
如果你说
t b(5);然后会有一个直接的初始化,没有复制省略,并且只有一个构造函数调用。您的类不需要复制构造函数即可编译此代码。
发布于 2013-10-07 12:39:10
由于没有采用int的赋值运算符,因此b = 3;被解释为
`b.operator=(t(3));`这将创建一个临时t实例,并在赋值返回后销毁它。这就是打印第一个de行的内容。最后,在main的末尾,b超出了作用域,它的析构函数被调用并打印第二行。
发布于 2013-10-07 12:40:38
也许你的程序中的一些痕迹可以帮助你理解发生了什么:
int main(){
t b=5; // as you expected, this call the constructor of your object.
cout<<"hello"<<endl;
b.print(); // as you could see, this call print() and print 5
b=3; // this is where the confusion begins. You didn't provide a way
// from your object to make an assigment from an integer, but you
// provide a way to construct an object from integer. So, your
// compiler will construct a temporary object, with 3 as parameter
// and use this object to do this assignment. Once this is a
// temporary object, it will be destructed at the end of this
// operation. That is why you are getting the message: 3 de
b.print(); // print 3 as expected
return 0; // call the destruct from the object that was assigned before
}https://stackoverflow.com/questions/19216972
复制相似问题