Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ auto_ptr 深入解析:輕量級智慧型指標

auto_ptr 是一個輕量級的智慧型指標,定義於 memory(而非 memory.h)之中,命名空間為 std。它最適合用來管理生命週期較短、或是不會被長距離傳遞的動態物件,理想的使用範圍最好侷限在單一函數內部,或某個類別的內部。

基本用法:

std::auto_ptr<int> pt(new int(10));
pt.reset(new int(11));

成員函數

有三個函數特別重要:

(1) get:取得內部物件的指標。由於它已經重載了 () 運算子,因此 sp 與 sp.get() 是等價的。例如 auto_ptr<int> sp(new int(1));,此時 sp 就等於 sp.get()。

(2) release:放棄內部物件的所有權,將內部指標清空,並回傳該內部物件的指標,這個指標需要你自己手動釋放。

std::auto_ptr<int> ap0(new int(1));
int* pa = ap0.release();
delete pa; // 需手動釋放

(3) reset:銷毀內部物件並接手新物件的責任(若使用預設參數,也就是不帶任何物件,則等同清空所有權)。

此外,它的建構子被宣告為 explicit,因此不能用賦值符對它賦值(也就是不能寫成 auto_ptr<int> p = new int; 這種形式)。

auto_ptr 的特性

(1) auto_ptr 的物件所有權是獨占的。

auto_ptr 的拷貝建構子與賦值運算子所接受的參數型別,都是「非 const 的引用」(一般情況我們會用 const 引用),原因就在於它內部需要呼叫 release 把原有物件釋放,再換上新物件。結果就是動態物件的所有權被轉移了,新的 auto_ptr 獨占了該物件。被拷貝的物件在過程中遭到修改,拷貝者與被拷貝者並非等價。以下用法就會出錯:

std::auto_ptr<int> pt1(new int(10));
std::auto_ptr<int> pt2 = pt1;
printf("pt1:%d\n", pt1); // 此時會印出 0
printf("pt1 value:%d\n", *pt1); // 錯誤,物件已釋放

(2) 不能把 auto_ptr 放進標準容器。因為標準庫容器沒有防備這種拷貝行為,會導致原 auto_ptr 內的物件被釋放,造成難以察覺的錯誤。

使用 auto_ptr 的注意事項

(1) auto_ptr 不能指向陣列
(2) auto_ptr 不能共享所有權
(3) auto_ptr 不能透過複製操作來初始化
(4) auto_ptr 不能放進容器中使用
(5) auto_ptr 不能作為容器的成員
(6) 別讓兩個智慧型指標管理同一個原生指標(對所有智慧型指標都成立):

int* p = new int;
auto_ptr<int> ap1(p);
auto_ptr<int> ap2(p); // 錯誤,p 不能交給第二個智慧型指標,會導致 p 被釋放兩次

底下是 VC 中的原始碼實作,可從中觀察它如何以非 const 引用完成所有權轉移:

template<class _Ty>
class auto_ptr {  // wrap an object pointer to ensure destruction
public:
    typedef auto_ptr<_Ty> _Myt;
    typedef _Ty element_type;

    explicit auto_ptr(_Ty *_Ptr = 0) _THROW0()
        : _Myptr(_Ptr) {  // construct from object pointer
    }

    auto_ptr(_Myt& _Right) _THROW0()
        : _Myptr(_Right.release()) {  // construct by assuming pointer from _Right auto_ptr
    }

    auto_ptr(auto_ptr_ref<_Ty> _Right) _THROW0() {  // construct by assuming pointer from _Right auto_ptr_ref
        _Ty *_Ptr = _Right._Ref;
        _Right._Ref = 0;  // release old
        _Myptr = _Ptr;    // reset this
    }

    template<class _Other>
    operator auto_ptr<_Other>() _THROW0() {  // convert to compatible auto_ptr
        return (auto_ptr<_Other>(*this));
    }

    template<class _Other>
    operator auto_ptr_ref<_Other>() _THROW0() {  // convert to compatible auto_ptr_ref
        _Other *_Cvtptr = _Myptr;  // test implicit conversion
        auto_ptr_ref<_Other> _Ans(_Cvtptr);
        _Myptr = 0;  // pass ownership to auto_ptr_ref
        return (_Ans);
    }

    template<class _Other>
    _Myt& operator=(auto_ptr<_Other>& _Right) _THROW0() {  // assign compatible _Right (assume pointer)
        reset(_Right.release());
        return (*this);
    }

    template<class _Other>
    auto_ptr(auto_ptr<_Other>& _Right) _THROW0()
        : _Myptr(_Right.release()) {  // construct by assuming pointer from _Right
    }

    _Myt& operator=(_Myt& _Right) _THROW0() {  // assign compatible _Right (assume pointer)
        reset(_Right.release());
        return (*this);
    }

    _Myt& operator=(auto_ptr_ref<_Ty> _Right) _THROW0() {  // assign compatible _Right._Ref (assume pointer)
        _Ty *_Ptr = _Right._Ref;
        _Right._Ref = 0;  // release old
        reset(_Ptr);      // set new
        return (*this);
    }

    ~auto_ptr() {  // destroy the object
        delete _Myptr;
    }

    _Ty& operator*() const _THROW0() {  // return designated value
        #if _ITERATOR_DEBUG_LEVEL == 2
        if (_Myptr == 0)
            _DEBUG_ERROR("auto_ptr not dereferencable");
        #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
        return (*get());
    }

    _Ty *operator->() const _THROW0() {  // return pointer to class object
        #if _ITERATOR_DEBUG_LEVEL == 2
        if (_Myptr == 0)
            _DEBUG_ERROR("auto_ptr not dereferencable");
        #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
        return (get());
    }

    _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
};
Copyright © Linux教程網 All Rights Reserved