auto_ptr的简单实现
生活随笔
收集整理的這篇文章主要介紹了
auto_ptr的简单实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>
#include <stack>
#include <stdio.h>using namespace std;template <class T>
class AutoPtr{
private:T *m_ptr;
public:explicit AutoPtr(T *p=0): m_ptr(p){}AutoPtr (AutoPtr &a):m_ptr(a.release()){}//拷貝構造函數,將原值拷貝,并設為0AutoPtr &operator = (AutoPtr &a) {if(this == &a)return *this;delete m_ptr;m_ptr = a.release();return *this;}~AutoPtr() {delete m_ptr;}T& operator *(){return *m_ptr;}T* operator ->() {return m_ptr;}T *get() {return m_ptr;}T* release() {//返回指針,并自己設為0T *tmp = m_ptr;m_ptr = 0;return tmp;}void reset(T *p = 0) {if (p != m_ptr) {delete m_ptr;m_ptr = p;}}};int main() {AutoPtr<int > t(new int(1));
}
1.????auto_ptr重載了操作符&,*和->。不要被語法誤導,記住pstr是一個對象,不是一個指針。只是它重載了這些操作符后,?使用上相指針一樣.
2.????不要將auto_ptr對象作為STL容器的元素。C++標準明確禁止這樣做,否則可能會碰到不可預見的結果
3.????不要將數組作為auto_ptr的參數,?可以理解到在auto_ptr中,?使用delete,?但沒有使用delete [].
4. auto_ptr不能作為容器的成員。
5.?不能通過賦值操作來初始化auto_ptr
std::auto_ptr<int> p(new int(42));?????// OK
std::auto_ptr<int> p = new int(42);????// ERROR
這是因為auto_ptr?的構造函數被定義為了explicit
總結
以上是生活随笔為你收集整理的auto_ptr的简单实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全排列算法的字典序排列
- 下一篇: 局部最小点