auto_ptr源碼 const auto_ptr保證擁有權不能轉移的實現原理?
-----------------------------------------------------------------------------------------------
在《C++標準程序庫》p55,提到了auto_ptr使用了一個技巧,能夠copy和復制non-const auto_ptr,但不可以copy和復制const atuo_ptr。
//auto_ptr的源碼:
template
struct auto_ptr_ref
{
_Tp1* _M_ptr;
explicit
auto_ptr_ref(_Tp1* __p): _M_ptr(__p) { }
};
template
class auto_ptr
{
private:
_Tp* _M_ptr;
public:
typedef _Tp element_type;
explicit
auto_ptr(element_type* __p = 0) throw() : _M_ptr(__p) { }
auto_ptr(auto_ptr& __a) throw() : _M_ptr(__a.release()) { }
template
auto_ptr(auto_ptr<_Tp1>& __a) throw() : _M_ptr(__a.release()) { }
auto_ptr&
operator=(auto_ptr& __a) throw()
{
reset(__a.release());
return *this;
}
template
auto_ptr&
operator=(auto_ptr<_Tp1>& __a) throw()
{
reset(__a.release());
return *this;
}
~auto_ptr() { delete _M_ptr; }
element_type&
operator*() const throw()
{
_GLIBCXX_DEBUG_ASSERT(_M_ptr != 0);
return *_M_ptr;
}
element_type*
operator->() const throw()
{
_GLIBCXX_DEBUG_ASSERT(_M_ptr != 0);
return _M_ptr;
}
element_type*
get() const throw() { return _M_ptr; }
element_type*
release() throw()
{
element_type* __tmp = _M_ptr;
_M_ptr = 0;
return __tmp;
}
void
reset(element_type* __p = 0) throw()
{
if (__p != _M_ptr)
{
delete _M_ptr;
_M_ptr = __p;
}
}
auto_ptr(auto_ptr_ref __ref) throw()
: _M_ptr(__ref._M_ptr) { }
auto_ptr&
operator=(auto_ptr_ref __ref) throw()
{
if (__ref._M_ptr != this->get())
{
delete _M_ptr;
_M_ptr = __ref._M_ptr;
}
return *this;
}
template
operator auto_ptr_ref<_Tp1>() throw()
{ return auto_ptr_ref<_Tp1>(this->release()); }
template
operator auto_ptr<_Tp1>() throw()
{ return auto_ptr<_Tp1>(this->release()); }
};//VC7中的
---------------------------------------------------------------------------------------------------------------
// TEMPLATE CLASS auto_ptr
template
class auto_ptr;
template
struct auto_ptr_ref
{ // proxy reference for auto_ptr copying
auto_ptr_ref(auto_ptr<_Ty>& _Right)
: _Ref(_Right)
{ // construct from compatible auto_ptr
}
auto_ptr<_Ty>& _Ref; // reference to constructor argument
};
template
class auto_ptr
{ // wrap an object pointer to ensure destruction
public:
typedef _Ty element_type;
explicit auto_ptr(_Ty *_Ptr = 0) _THROW0()
: _Myptr(_Ptr)
{ // construct from object pointer
}
auto_ptr(auto_ptr<_Ty>& _Right) _THROW0()
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right auto_ptr
}
auto_ptr(auto_ptr_ref<_Ty> _Right) _THROW0()
: _Myptr(_Right._Ref.release())
{ // construct by assuming pointer from _Right auto_ptr_ref
}
template
operator auto_ptr<_Other>() _THROW0()
{ // convert to compatible auto_ptr
return (auto_ptr<_Other>(*this));
}
template
operator auto_ptr_ref<_Other>() _THROW0()
{ // convert to compatible auto_ptr_ref
return (auto_ptr_ref<_Other>(*this));
}
template
auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0()
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}
template
auto_ptr(auto_ptr<_Other>& _Right) _THROW0()
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right
}
auto_ptr<_Ty>& operator=(auto_ptr<_Ty>& _Right) _THROW0()
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}
auto_ptr<_Ty>& operator=(auto_ptr_ref<_Ty>& _Right) _THROW0()
{ // assign compatible _Right._Ref (assume pointer)
reset(_Right._Ref.release());
return (*this);
}
~auto_ptr()
{ // destroy the object
delete _Myptr;
}
_Ty& operator*() const _THROW0()
{ // return designated value
return (*_Myptr);
}
_Ty *operator->() const _THROW0()
{ // return pointer to class object
return (&**this);
}
_Ty *get() const _THROW0()
{ // return wrapped pointer
return (_Myptr);
}
_Ty *release() _THROW0()
{ // return wrapped pointer and give up ownership
_Ty *_Tmp = _Myptr;
_Myptr = 0;
return (_Tmp);
}
void reset(_Ty* _Ptr = 0)
{ // destroy designated object and store new pointer
if (_Ptr != _Myptr)
delete _Myptr;
_Myptr = _Ptr;
}
private:
_Ty *_Myptr; // the wrapped object pointer
};
----------------------------------------------------------------------------------------------------------
C++中的auto_ptr (修改版本) stl 文件中的 std::auto_ptr 在C++中的故事特別多, 在它的演變過程中至少出現了3個版本.
http://www.josuttis.com/libbook/auto_ptr.html 這個連接里面有它完整的故事.
VC6中STL帶的auto_ptr( 帶owner字段)的版本應該就是文中說的Version 2.
最新的Version里面包含了一個auto_ptr_ref, 這個是當將auto_ptr作為函數返回值和函數參數時需要引入的
一個"額外間接層".
下面是它的一些說明:
auto_ptr的拷貝構造函數和一般我們常見的不同, 它的參數rhs并不是const reference, 而是refence,
auto_ptr( /*const */ auto_ptr& rhs)
{
...
}
假設我們需要將一個auto_ptr作為某個函數的返回值, 例如
auto_ptr source()
{
return auto_ptr(new int(3));
}
那么我們如何在caller中得到返回的結果呢?
理所當然的語法是:
auto_ptr p( source() ); (拷貝構造函數)
或者
auto_ptr p = source(); (拷貝構造函數)
或者
auto_ptr p = ...; (operator=)
p = source();
但是如果沒有auto_ptr_ref的存在, 上面這些行實際上應該是一個編譯錯誤(VC6不報錯), 原因是:
C++中有左值/右值之分, 函數如果返回值, 那么是r-value. 右值作為reference函數參數時, 只能是const reference.
因此source函數返回的auto_ptr作為rhs實參調用auto_ptr的拷貝構造函數時, 只能是const refernce, 但是
這個函數的簽名需要rhs為reference, 因此無法編譯.
舉個最簡單的例子:
有函數:
int foo() { return 0; }
void bar(int & i) { }
調用
int& i = foo() ; //錯誤
const int& i = foo(); //OK
bar(foo()) //錯誤
同理, 拷貝構造函數不過是一個特殊的"函數"而已, 我們上面的source函數返回的auto_ptr對象也只能作為一個
const auto_ptr&, 但是這個拷貝構造函數需要的參數原型是auto_ptr&, 而不是const auto_ptr& .
因此auto_ptr引入了一個'額外的間接層' auto_ptr_ref, 來完成一個從r-value到l-value之間的過渡.
基本的思路是;
提供另外一個構造函數, 接受一個以值傳遞的auto_ptr_ref:
auto_ptr( auto_ptr_ref ref)
{
....
}
然后在auto_ptr類中, 提供一個自動轉型的函數
operator auto_ptr_ref ()
{
.....
}
這樣, source返回一個auto_ptr, 編譯器嘗試調用拷貝構造函數, 發現參數不必配(期望const), 然后發現了一個自動轉型的
operator auto_ptr_ref()函數, 而后又發現通過調用該自動轉型得到一個auto_ptr_ref對象后, 可以調用caller的
auto_ptr的以auto_ptr_ref為參數的非explicit的構造函數, 完成了一個auto_ptr到另外一個auto_ptr之間的復制過程.
注意一點: operator auto_ptr_ref () 不是const成員函數.
C++語法規則中對于臨時變量的r-value有個詭秘的地方就是:
如果你需要將r-value保存在一個reference中, 或者作為某個refence的函數參數, 那么必須為const reference,
但是你也可以在一個完整的表達式中直接使用這個臨時變量, 這種情況下該臨時變量實際上并不是作為const reference對待,
因為你可以調用它的非const成員函數. 例如:
class Integer
{
public:
void zero() { i = 0; }
private:
int i;
};
class Integer
{
public:
void zero() { i = 0; }
private:
int i;
};
Integer().zero(); //創建一個Integer的臨時變量, 然后調用非const成員函數.
這樣, auto_ptr p( source() );
實際上發生的事情就是:
auto_ptr p( source().operator auto_ptr_ref());
通過source()函數得到一個臨時的auto_ptr對象, 然后調用其中的自動轉換函數得到一個auto_ptr_ref,
即使該轉型函數是非const成員函數仍然可行.
然后調用 p 對象的以auto_ptr_ref為參數的構造函數進行復制.
然后, source()函數創建的臨時對象在整個表達式結束后被析構, 當然這個時候這個臨時對象內部的指針已經被reset(0)了,
因為該指針的擁有權已經被p接管了. (否則會重復刪除)
std::auto_ptr在很多情況下是很便利的, 例如一個函數內部需要通過new分配一個結構, 那么誰來釋放是一個問題,
一種原則是誰分配, 誰釋放, 但是對于這種情況顯然不合適.
利用auto_ptr就簡單得多了: 誰擁有誰釋放, 誰都不要那么就編譯器自動釋放它. 例如
有個函數:
auto_ptr create_sth()
{
auto_ptr p(new sth);
return p;
}
調用1:
auto_ptr p = create_sth();
...
p退出作用域, 自動釋放.
調用2:
create_sth();
沒有人接受這個返回的對象, 那么編譯器自動會調用auto_ptr的析構函數釋放之.
sink也是一個作用:
例如我已經擁有一個auto_ptr對象的指針, 那么我可以定義一個sink函數, 原型如下:
void sink(auto_ptr p)
{
}
正如sink名字暗示的一樣, sink函數起到一個吸收作用, 將某個外部的auto_ptr對象吸收過來,類似于宇宙中的"黑洞".
例如:
auto_ptr p(new sth);
sink(p);
//這里, p指向null了, p所指的sth對象已經被sink函數"吸收"了.
當然為了防止這種情況在你不注意的情況下發生, 你可以
const auto_ptr p(new sth);
sink(p); //編譯錯誤
auto_ptr p2 = p; //編譯錯誤
這樣, 一個const auto_ptr的對象一旦構造完成, 永遠不會失去對該對象的擁有權. "一旦擁有, 從不失去".
當然auto_ptr最重要的作用, 也是它的原始目的是為了提供異常安全.
auto_ptr
動態內存使用最多的是在C++應用程序的代碼中。有過編程經驗的程序員雖然都知道new操作符的使用一定要與delete匹配,在某些場合仍然可能有內存溢出。當異常被擲出時,程序的正常控制流程被改變,因此導致潛在的內存溢出。例如,
void g() //可能擲出
{
if (some_condition == false)
throw X();
}
void func()
{
string * pstr = new string;
g(); //如果 g 擲出一個異常,內存溢出
delete pstr; //如果 g 擲出一個異常,則此行為不能達到的代碼行。
}
int main()
{
try
{
func();
}
catch(...)
{}
}
當 g 擲出一個異常,異常處理機制展開堆棧:g()退出,同時控制被轉移到 main() 的 catch(...)代碼塊。這時,無論怎樣,func()中的delete語句都不會被執行,由此導致pstr的內存溢出。要是使用局部自動串變量,而不是使用動態分配-內存溢出就不會出現了:
string str; //局部自動對象
g(); //沒有內存溢出
許多數據重要的結構以及應用,象鏈表,STL容器,串,數據庫系統以及交互式應用必須使用動態內存分配,因此仍然冒著萬一發生異常導致內存溢出的風險。C++標準化委員會意識到了這個漏洞并在標準庫中添加了一個特殊的類模板,它就是std::auto_ptr,其目的是促使動態內存和異常之前進行平滑的交互。Auto_ptr保證當異常擲出時分配的對象(即:new操作符分配的對象)能被自動銷毀,內存能被自動釋放。下面我們就來討論使用動態內存時,如何正確和有效地使用auto_ptr來避免資源溢出。這個技術適用于文件,線程,鎖定以及與此類似的資源。
Auto_ptr的定義可以在中找到。與標準庫中其它的成員一樣,它被聲明在命名空間std::中。當你實例化auto_ptr對象時,對它進行初始化的方法是用一個指針指向動態分配的對象,下面是實例化和初始化auto_ptr對象的例子:
include
#include
using namespace std;
void func()
{
auto_ptr pstr (new string); /* 創建并初始化auto_ptr */
}
auto_ptr后面的尖括弧里指定auto_ptr指針的類型,在這個例子中是string。然后auto_ptr句柄的名字,在這個例子中是pstr。最后是用動態分配的對象指針初始化這個實例。注意你只能使用auto_ptr構造器的拷貝,也就是說,下面的代碼是非法的:
auto_ptr pstr = new string; //編譯出錯
Auto_ptr是一個模板,因此它是完全通用的。它可以指向任何類型的對象,包括基本的數據類型:
auto_ptr pi (new int);
一旦你實例化一個auto_ptr,并用動態分配的對象地址對它進行了初始化,就可以將它當作普通的對象指針使用,例如:
*pstr = "hello world"; //賦值
pstr->size(); //調用成員函數
之所以能這樣做是因為auto_ptr重載了操作符&,*和->。不要被語法誤導,記住pstr是一個對象,不是一個指針。
auto_ptr是如何解決前面提到的內存溢出問題呢?auto_ptr的析構函數自動摧毀它綁定的動態分配對象。換句話說,當pstr的析構函數執行時,它刪除構造pstr期間創建的串指針。你絕不能刪除auto_ptr,因為它是一個本地對象,它的析構函數是被自動調用的。讓我們看一下函數func()的修訂版本,這次使用了auto_ptr:
void func()
{
auto_ptr pstr (new string);
g(); //如果g()擲出異常,pstr 被自動摧毀
}
C++保證在堆棧展開過程中,自動存儲類型的對象被自動摧毀。因此,如果g()擲出異常,pstr的析構函數將會在控制被轉移到catch(...)塊之前執行。因為pstr的析構函數刪除其綁定的串指針,所以不會有內存溢出發生。這樣我們在使用動態分配對象時,利用auto_ptr就實現了自動和安全的本地對象。
如何避免使用auto_ptr的缺陷
auto_ptr并不是完美無缺的,它的確很方便,但也有缺陷,在使用時要注意避免。首先,不要將auto_ptr對象作為STL容器的元素。C++標準明確禁止這樣做,否則可能會碰到不可預見的結果(在另文中討論)。
auto_ptr的另一個缺陷是將數組作為auto_ptr的參數:
auto_ptr pstr (new char[12] ); //數組;為定義
記住不管什么時候使用數組的new操作時,必須要用delete[]來摧毀數組。因為auto_ptr的析構函數只對非數組類型起作用。所以數組是不能被正確摧毀的話,程序的行為是不明確的。總之,auto_ptr控制一個由new分配的單對象指針,僅此而已。
--------------------------------------------------------------------------------------------------
Misusing auto_ptrs
auto_ptrs satisfy a certain need; namely, to avoid resource leaks when exception handling is used. Unfortunately, the exact behavior of auto_ptrs changed in the past and no other kind of smart pointers are provided in the C++ standard library, so people tend to misuse auto_ptrs. Here are some hints to help you use them correctly:
-
auto_ptrs cannot share ownership.
An auto_ptr must not refer to an object that is owned by another auto_ptr (or other object). Otherwise, if the first pointer deletes the object, the other pointer suddenly refers to a destroyed object, and any further read or write access may result in disaster.
-
auto_ptrs are not provided for arrays.
An auto_ptr is not allowed to refer to arrays. This is because an auto_ptr calls delete instead of delete [] for the object it owns. Note that there is no equivalent class in the C++ standard library that has the auto_ptr semantics for arrays. Instead, the library provides several container classes to handle collections of data (see Chapter 5).
-
auto_ptrs are not "universal smart pointers."
An auto_ptr is not designed to solve other problems for which smart pointers might be useful. In particular, they are not pointers for reference counting. (Pointers for reference counting ensure that an object gets deleted only if the last of several smart pointers that refer to that object gets destroyed.)
-
auto_ptrs don't meet the requirements for container elements.
An auto_ptr does not meet one of the most fundamental requirements for elements of standard containers. That is, after a copy or an assignment of an auto_ptr, source and sink are not equivalent. In fact, when an auto_ptr is assigned or copied, the source auto_ptr gets modified because it transfers its value rather than copying it. So you should not use an auto_ptr as an element of a standard container. Fortunately, the design of the language and library prevents this misuse from compiling in a standard-conforming environment.