【C++】make_shared, const與指針的關系


、boost 和 std
boost和std庫中都有智能指針shared_ptr, make_shared.
且std中的智能指針模塊來源於boost中的智能指針。
 
二、make_shared

構造shared_ptr時,比new更安全、更高效的方法是make_shared(使用系統默認new操作),allocate_shared(允許用戶指定allocate函數)。

優勢:new會有兩次內存分配,一次是生成對象( new int() ),一次是引用計數

make_shared把兩次合並成了一次。

boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");
std::cout << *x; 
// 構造一個string指針
boost::shared_ptr<vector<int> > spv = boost::make_shared<vector<int> >(10, 2);
// 構造一個vector指針

 

二、const 與指針的關系

2.1 裸指針與const

2.1.1 指向常量的指針,即指針指向的內容不可以改變。有2種形式,

const int* raw_ptr;
int const * raw_ptr;

此時指針可以指向任意內容。在初始化指針的時候,不需要給指針賦值

 

2.1.2 常量指針,即不可以改變指針的指向。只有1種形式,

int a = 3;
int* const raw_ptr = &a;

由於指針的指向不可以改變,因此在初始化時必須給常量指針賦值

 

2.1.3 指向常量的常指針

int a = 2;
int b = 3;
const int* const raw_ptr = &a;
int const* const raw_ptr = &b;

 

2.2 智能指針與const

2.2.1 指向常量的智能指針

std::shared_ptr<const T> k_s_ptr;

 

2.2.2 常量智能指針

const std::shared_ptr<T> k_s_ptr = boost::make_shared<T>();

 


免責聲明!

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



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