【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