#include <memory>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
auto_ptr<int > api ,api2;
api = auto_ptr<int>( new int(10) );
cout<<"api:"<<*api<<endl;
/*
api對象的布局:一個int數表示該對象是否有效。(==1有效,==0無效)
一個指標 指向int資料(因為你在聲明api時已經說了它時指向int的)
*/
api2 = api; //傳遞性:執行完本句之後,api無效,同時api2有效,api2的另一個欄位指向int
auto_ptr<string > aps1,aps2;
aps1 = auto_ptr<string>(new string("pig") );
cout<<"aps1:"<<*aps1<<endl;
return 0;
}
vc6的說明:
auto_ptr
template<class T> class auto_ptr {public: typedef T element_type; explicit auto_ptr(T *p = 0) throw(); auto_ptr(const auto_ptr<T>& rhs) throw(); auto_ptr<T>& operator=(auto_ptr<T>& rhs) throw(); ~auto_ptr(); T& operator*() const throw(); T *operator->() const throw(); T *get() const throw(); T *release() const throw(); };
The class describes an object that stores a pointer to an allocated object of type T. The stored pointer must either be null or designate an object allocated by a new expression. The object also stores an ownership indicator. An object constructed with a non-null pointer owns the pointer. It transfers ownership if its stored value is assigned to another object. The destructor for auto_ptr<T> deletes the allocated object if it owns it. Hence, an object of class auto_ptr<T> ensures that an allocated object is automatically deleted when control leaves a block, even via a thrown exception.
//好了,估計說了這麼多 ,應該知道 auto_ptr的功能和不足了。
//再看看以下我 轉過來的文章
STL中的auto_ptr指標是為瞭解決記憶體流失問題而設計的。它嚴格限制了指標擁有對指向對象的所有權。auto_ptr指標和普通指標的差別在於對指向對象所有權的處理不同。auto_ptr指標是“傳遞”所有權,而普通指標是“共用”所有權。看下面例子:
std::auto_ptr<int> p1(new int(24));std::auto_ptr<int> p2;int *q1 = new int(12);int *q2;p2 = p1;q2 = q1; 經過兩次賦值後,對於auto_ptr,p1為NULL,*p2為24;對於普通指標,*p1, *p2均為12。第一次賦值,p1把指向對象的所有權傳遞給了p2, p1不再擁有指向對象的所有權。而第二次賦值,q2和q1共用了對同一對象的所有權。因此,對於auto_ptr,一個對象只可能被一個智能指標指向,這樣可有效避免記憶體流失問題。但是同時會引起新問題。看下面例子:template<class T>void BadPrint(std::auto_ptr<T> p){ if (p.get() == NULL) { std::cout<<NULL; } else { std::cout<<*p; }} 然後我如下使用BadPrint函數:std::auto_ptr<int> q(new int(18));BadPrint(q);*q = 12; 該程式並未像我們所期望的一樣:*q的值為12,而是會出現runtime error,why?因為我們把q作為函數參數傳給了BadPrint,因此傳遞完成後q不再擁有對指向對象的所有權,而函數內部的局部變數p會接管q所指向對象的所有權,當函數執行完畢退出時,p的生命期截止同時delete所指向對象。因此q實際變為NULL,所以出錯。如何避免出錯?使用auto_ptr的引用?即 void BadPrint(std::auto_ptr<T> &p)。這是相當糟糕的一種做法。對智能指標使用引用混淆了所有權的問題。它導致所有權有可能被傳遞了,也可能沒有被傳遞。無論如何應當避免對auto_ptr使用引用。 可見智能指標並非對任何情況都智能。使用auto_ptr要知道:1. 智能指標不能共用指向對象的所有權2. 智能指標不能指向數組。因為其實現中調用的是delete而非delete[]3. 智能指標不是萬能的4. 智能指標不能作為容器類的元素。例如:template<class T>void container::insert(const T &value){ .......... X = value; ..........}事實上在stl中,所有的container要內部拷貝所傳參數的值時都是傳的const類型的值。因此無法用auto_ptr傳進去。、、、、、、、、、、、、、、、、、、、、、一句話: //一句話,假定有一個動態分配的int空間,則在一個時刻只能有一個auto_ptr指標指向他!
這就是所有權的獨佔性