一文掌握 C 智能指針的使用
時間:2021-10-29 16:07:44
手機看文章
掃描二維碼
隨時隨地手機看文章
[導讀]來自:現(xiàn)代C教程:高速上手C11/14/17/20鏈接:https://changkun.de/modern-cpp/zh-cn/05-pointers/index.htmlRAII與引用計數(shù)了解?Objective-C/Swift?的程序員應該知道引用計數(shù)的概念。引用計數(shù)這種計...
RAII 與引用計數(shù)
了解 Objective-C/Swift 的程序員應該知道引用計數(shù)的概念。引用計數(shù)這種計數(shù)是為了防止內(nèi)存泄露而產(chǎn)生的。
。
注意:引用計數(shù)不是垃圾回收,引用計數(shù)能夠盡快收回不再被使用的對象,同時在回收的過程中也不會造成長時間的等待, 更能夠清晰明確的表明資源的生命周期。
std::shared_ptr
std::shared_ptr 是一種智能指針,它能夠記錄多少個 shared_ptr 共同指向一個對象,從而消除顯式的調用 delete,當引用計數(shù)變?yōu)榱愕臅r候就會將對象自動刪除。
但還不夠,因為使用 std::shared_ptr 仍然需要使用 new 來調用,這使得代碼出現(xiàn)了某種程度上的不對稱。
std::make_shared 就能夠用來消除顯式的使用 new,所以 std::make_shared 會分配創(chuàng)建傳入?yún)?shù)中的對象, 并返回這個對象類型的 std::shared_ptr 指針。例如:
#include
#include
void foo(std::shared_ptr<int> i)
{
(*i) ;
}
int main()
{
// auto pointer = new int(10); // illegal, no direct assignment
// Constructed a std::shared_ptr
auto pointer = std::make_shared<int>(10);
foo(pointer);
std::cout << *pointer << std::endl; // 11
// The shared_ptr will be destructed before leaving the scope
return 0;
}
std::shared_ptr 可以通過 get() 方法來獲取原始指針,通過 reset() 來減少一個引用計數(shù), 并通過 use_count() 來查看一個對象的引用計數(shù)。例如:
auto pointer = std::make_shared<int>(10);
auto pointer2 = pointer; // 引用計數(shù) 1
auto pointer3 = pointer; // 引用計數(shù) 1
int *p = pointer.get(); // 這樣不會增加引用計數(shù)
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 3
pointer2.reset();
std::cout << "reset pointer2:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 2
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0, pointer2 已 reset
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 2
pointer3.reset();
std::cout << "reset pointer3:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 1
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 0, pointer3 已 reset
std::unique_ptr
std::unique_ptr 是一種獨占的智能指針,它禁止其他智能指針與其共享同一個對象,從而保證代碼的安全:
std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 從 C 14 引入
std::unique_ptr<int> pointer2 = pointer; // 非法
make_unique 并不復雜,C 11 沒有提供 std::make_unique,可以自行實現(xiàn):
template<typename T, typename ...Args>
std::unique_ptrmake_unique( Args