有人在C ++析构函数类调用时向我解释吗?它何时自动调用,何时需要显式调用? 我尝试了下面的代码,但结果出乎意料。
class V{
private:double x,y,z;
public:
V(){
x=y=x=0.0;
}
V(double x=0.0,double y=0.0,double z=0.0):z(z){
this->x=x;
(*this).y=y;
return;
}
V(const V &src){
x=src.x;
y=src.y;
z=src.z;
return;
}
void print(){
cout<<x<<" "<<y<<" "<<z<<endl;
}
~V(){
cout<<"Destructor called"<<endl;
}
};
int main(){
V *p;
p=new V(1,2,3);
/*delete p;
Why is the destructor not called automatically for dynamically allocated object p after the program ends? If delete p is included destructor is called. Why is it so?*/
V(1,2,3).print();
/*Here the object does not have any name but still the destructor is called. Why does this happen?*/
V vec3(V(1,2,3));
/*Here only one destructor was called but I was expecting two.One for object object **vec3** and other for the nameless object **V(1,2,3)** as in above case. Why did this happen?*/
}