|
本来以为类的析构函数就是释放掉某个对象,释放完了该内存应该也释放了,就像通过指针delete一样,但是做了个小测试发现有点问题:
- #include <iostream>
- using namespace std;
- class base
- {
- public:
- base(int a)
- {cout<<a<<" "<<"base con"<<endl;}
- virtual ~base()
- {cout<<a<<" "<<this<<" "<<"base ~con"<<endl;}
- private:
- int a;
- base &operator=(const base &a);
- };
- class derived:public base
- {
- public:
- derived(int a):base(a)
- {cout<<"d1 con"<<endl;}
- ~derived()
- {cout<<"d1 ~con"<<endl;}
- private:
- derived &operator=(const derived &d);
- };
- void main()
- {
- //base *b=new derived(2);
- //delete b;
- derived d(2);
- d.~derived();
- }
复制代码
假如采用new和delete方式,结果和我想象的一样,输出构造和析构函数各一次,然后如果采用创建对象然后调用其析构函数的方式则会输出两遍析构函数,求解

 |
|