(原)C++智能指针——释放器(in linux, g++)
2012-08-14 09:57
232 查看
我的记录:
1.指定了释放器,就不会去直接调用析构函数。因为释放器就一个。不指定的话析构函数就是释放器.
2.STL智能指针对内置内型的支持不如class:比如shared_ptr<char> s(new char[10]); memset(s, 0x00, 10);//error! 只能memset(s.get(), ....了。
3. auto_ptr不能指定释放器.
$ g++ main.cpp
1.指定了释放器,就不会去直接调用析构函数。因为释放器就一个。不指定的话析构函数就是释放器.
2.STL智能指针对内置内型的支持不如class:比如shared_ptr<char> s(new char[10]); memset(s, 0x00, 10);//error! 只能memset(s.get(), ....了。
3. auto_ptr不能指定释放器.
#include "iostream" #include <tr1/memory> using namespace std; using std::tr1::shared_ptr; using std::auto_ptr; class C { public: C() { cout<<"C()"<<endl; buf = new char[10]; } ~C() { cout<<"~C()"<<endl; if(buf) { cout<<"~C() delete []buf."<<endl; delete [] buf; } } static void MyRelease(C * pC) { cout<<"MyRelease()"<<endl; cout<<"MyRelease() delete [] buf."<<endl; delete [] pC->buf; pC->buf = NULL; cout<<"MyRelease() delete C:"; delete pC;//call ~C(). } private: char * buf; }; int main() { cout<<"std::tr1::shared_ptr<C>:"<<endl; { C * a = new C; shared_ptr<C> shareC(a, C::MyRelease); } cout<<"<- shared_ptr test ended.\n"<<endl; cout<<"std::tr1::shared_ptr<C> copy test"<<endl; { shared_ptr<C> shareC(new C, C::MyRelease); shared_ptr<C> shareC2 = shareC; } cout<<"<- shared_ptr copy test ended.\n"<<endl; cout<<"std::auto_ptr<C>:"<<endl; C * b = new C; auto_ptr<C> autoC(b); cout<<"return 0;"<<endl; return 0; }
$ g++ main.cpp
相关文章推荐
- [置顶]C++ 引用计数技术及智能指针的简单实现
- C++ 智能指针 tutorials
- C++ 智能指针Auto_PTR 分析http://www.cnblogs.com/skyofbitbit/p/3649776.html
- 简单模拟实现c++智能指针-指针移交控制权
- C++学习之智能指针
- C++智能指针shared_ptr分析
- 改善C++ 程序的150个建议学习之建议34:用智能指针管理通过new创建的对象
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- 【C++智能指针 auto_ptr】
- C++ 智能指针详解(转)
- 读书笔记:C++中利用智能指针和值型类防止内存非法访问
- C++ 智能指针详解
- C++ 11智能指针之week_ptr
- 详解C++各种智能指针: auto_ptr, shared_ptr, weak_ptr, scoped_ptr
- C++ 最简单的 '智能指针' 的实现
- C++中智能指针的设计和使用
- [C/C++]_[中级]_[使用智能指针的方式释放malloc出来的堆空间]
- C++智能指针
- C++ 智能指针详解
- C++ 智能指针