智能指針std::unique_ptr


std::unique_ptr

1.特性

1) 任意時刻unique_ptr只能指向某一個對象,指針銷毀時,指向的對象也會被刪除(通過內置刪除器,通過調用析構函數實現刪除對象)

2)禁止拷貝和賦值(底層實現拷貝構造函數和復制構造函數 = delete),可以使用std::move()、unique_ptr.reset(...) 轉移對象指針控制權。

(由1決定,指針發生了拷貝就違反了第一條)

2.怎么實現禁止拷貝構造和賦值構造?

拷貝構造 和 賦值符‘=’ 對應函數 被刪除了,所以用不了。  (看下面的構造函數表)

default (1)
constexpr unique_ptr() noexcept; 
from null pointer (2)
constexpr unique_ptr (nullptr_t) noexcept : unique_ptr() {} 
from pointer (3)
explicit unique_ptr (pointer p) noexcept; 
from pointer + lvalue deleter (4)
unique_ptr (pointer p, typename conditional<is_reference<D>::value,D,const D&> del) noexcept; 
from pointer + rvalue deleter (5)
unique_ptr (pointer p, typename remove_reference<D>::type&& del) noexcept; 
move (6)
unique_ptr (unique_ptr&& x) noexcept; 
move-cast (7)
template <class U, class E> unique_ptr (unique_ptr<U,E>&& x) noexcept; 
move from auto_ptr (8)
template <class U> unique_ptr (auto_ptr<U>&& x) noexcept;拷貝構造

拷貝構造     

copy (deleted!) (9)

unique_ptr (const unique_ptr&)= delete;

 

復制作業(刪除!)(4)
unique_ptr&operator =(const unique_ptr&)= delete;

可以在IDE/編輯器中查看詳細實現:(下面是 GNU  g++的實現)

 

 

我們可以看到,拷貝和賦值函數被禁止實現(禁用)了。

更加詳細的內容參閱cppreference:

① std :: unique_ptr 構造   

② 賦值  


3. 使用

 1 #include <iostream>
 2 #include <memory>
 3 using namespace std;
 4 
 5 // unique_ptr::get vs unique_ptr::release
 6 int main() 
 7 {
 8     std::unique_ptr<int> foo; //foo - null
 9     std::unique_ptr<int> bar; //bar - null
10     int* p = nullptr;
11     foo = std::unique_ptr<int>(new int(100));// foo - 100
12     bar = std::move(foo); // foo轉移給bar bar - 100 foo - null
13     p = bar.get(); // p - 100 smart pointer.get()返回一個指向該對象的內置指針
14     foo.reset(bar.release()); // bar 放棄指針控制權,返回指針給foo foo - 100, bar已經不存在
15 
16     cout << "foo : " << *foo << endl;
17     cout << "p   : " << *p << endl;
18     delete p; //記得刪除,這也是使用智能指針的初衷之一---防止內存泄漏!!!
19 
20     if (bar)
21         cout << "bar : " << *bar << endl;
22     else
23         cout << "bar已經被釋放" << endl; //這里bar已經銷毀了,可能會報錯。
24 
25     return 0;
26 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM