1、C++中可不可以自动管理内存的释放功能?
2、C++里面的智能指针究竟是如何实现的?
3、以下代码去掉注释与未去掉注释的结果是什么?
#include<iostream> #include<memory> #include<new> using namespace std; void * operator new(size_t size,int data,char *flags) { return ::operator new(size); } void operator delete(void *tmp) { cout<<"delete"<<endl; free(tmp); } int main() { int *tmp=new (10,NULL)int[10]; //auto_ptr<int> pInt(tmp); return 0; } |
内存申请后最容易被人遗忘的操作就是内存的回收,一个良好的程序员在C/C++中必定记得的是一个new对应一个delete(其实new与delete未必申请与释放内存,想知道为什么,可以看我的博客中你真的了解NEW操作符吗:)),一个malloc对应一个free,那么C++中有没有自动回收内存的机制呢,答案是有
那就是auto_ptr指针,也许有些人压根就没听说过,也许有些人听说了但是嫌它的功能不够强大,改投了Boost库,作为C++语言的内置特性,还是有必要了解与分析一下,程序员都是比较懒的,释放内存就交给它吧:)
MSDN中关于它的定义如下:
Wraps a smart pointer around a resource that ensures the resource is destroyed automatically when control leaves a block. |
翻译过来的的意思就是资源的智能指针,当不再使用该资源时,能够自动释放该资源所占用的内存。
其源代码定义在<memory>这个文件中,如下:
template<class _Ty> class auto_ptr { public: typedef _Ty element_type; explicit auto_ptr(_Ty *_P = 0) _THROW0(): _Owns(_P != 0), _Ptr(_P) {} auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0() : _Owns(_Y._Owns), _Ptr(_Y.release()) {} auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0() {if (this != &_Y) {if (_Ptr != _Y.get()) {if (_Owns) delete _Ptr; _Owns = _Y._Owns; } else if (_Y._Owns) _Owns = true; _Ptr = _Y.release(); } return (*this); } ~auto_ptr() {if (_Owns) delete _Ptr; } _Ty& operator*() const _THROW0() {return (*get()); } _Ty *operator->() const _THROW0() {return (get()); } _Ty *get() const _THROW0() {return (_Ptr); } _Ty *release() const _THROW0() {((auto_ptr<_Ty> *)this)->_Owns = false; return (_Ptr); } private: bool _Owns; _Ty *_Ptr; }; |