c++ primer plus阅读笔记12---手动调用析构函数
2017-08-17 12:06
459 查看
再谈定位new运算符
我们来看代码:
上边的代码中,pc1和pc3都在堆上申请的buffer中,当调用delete []buffer时,会将buffer处的内存全部释放,但是delete []buffer并不知道里边还有个对象,所以不会调用该对象的析构函数,为了调用其析构函数,必须手动调用,pc1-> ~JustTestting();
我们来看代码:
#include <iostream> #include <string> #include <new> using namespace std; const int BUF=512; class JustTestting { private: string words; int number; public: JustTestting(const string &s="Just Testing",int n=0) { words=s; number=n; cout<<words<<" constructed\n"; } ~JustTestting() { cout<<words<<" destoryed\n"; } void Show()const { cout<<words<<","<<number<<endl; } }; int main() { char *buffer=new char[BUF]; JustTestting *pc1,*pc2; pc1=new(buffer)JustTestting; //pc1在堆上buffer处 pc2=new JustTestting("Heap1",20);//pc2在堆上 cout<<"Memory block address\n"<<"buffer:"<<(void *)buffer<<" Heap:"<<pc2<<endl; cout<<"Memory contents:\n"; cout<<pc1<<":"; pc1->Show(); cout<<pc2<<":"; pc2->Show(); JustTestting *pc3,*pc4; pc3=new(buffer)JustTestting("Bad Idea",6);//pc3在堆上buffer处 pc4=new JustTestting("Heap2",10); //pc4在堆上 cout<<"Memory contents:\n"; cout<<pc3<<":"; pc3->Show(); cout<<pc4<<":"; pc4->Show(); //pc1-> ~JustTestting(); delete pc 4000 1 pc3将会出错,这里需要手动调用pc1的析构函数 //pc3-> ~JustTestting(); delete pc2; delete pc4; delete []buffer; cout<<"done\n"; return 0; }
上边的代码中,pc1和pc3都在堆上申请的buffer中,当调用delete []buffer时,会将buffer处的内存全部释放,但是delete []buffer并不知道里边还有个对象,所以不会调用该对象的析构函数,为了调用其析构函数,必须手动调用,pc1-> ~JustTestting();
相关文章推荐
- c++primer plus阅读笔记(十)
- c++ primer plus阅读笔记13---虚函数 为什么要虚析构函数?
- C++ Primer Plus阅读笔记
- c++ primer plus阅读笔记14---虚基类
- c++ primer plus阅读笔记7---模板特化
- c++ primer plus阅读笔记2---结构体共用体枚举
- c++ primer plus阅读笔记10---定位new using namespace
- c++primer plus阅读笔记(五)
- C++primer plus阅读笔记第四章
- c++primer plus阅读笔记(六)
- 《C++ Primer Plus》10.3 类的构造函数和析构函数 学习笔记
- c++ primer plus阅读笔记3---指针问题
- c++ primer plus阅读笔记8---decltype
- c++ primer plus阅读笔记(三)
- c++primer plus阅读笔记(七)
- c++ primer plus阅读笔记4---struct
- 【学习笔记】C++primer plus 10. 11. 12. 对象
- c++ primer plus阅读笔记6---内联函数引用变量
- c++ primer plus阅读笔记11---深拷贝与浅拷贝
- 《C++ Primer Plus》14.3 多重继承 学习笔记