boost::shared_ptr boost::make_shared
来源:互联网 发布:美工招聘信息 编辑:程序博客网 时间:2024/06/07 06:39
1. boost::shared_ptr
1.1 shared_ptr作为一个动态分配的对象,当最后一个指向其内容的指针销毁(destroyed)或重置(reset),其指向的内容会被销毁(deleted)。
example:
shared_ptr<double[1024]> p1( new double[1024] );shared_ptr<double[]> p2( new double[n] );
1.2 避免使用未命名的shared_ptr临时保存类型,例如:
void f(shared_ptr<int>, int);int g();void ok(){ shared_ptr<int> p( new int(2) ); f( p, g() );}void bad(){ f( shared_ptr<int>( new int(2) ), g() );}
由于函数调用参数是无需的,有可能先执行new int(2) , 再执行 g(), 如果这是g()抛出异常,可能永远不能执行shared_ptr的构造函数。推荐使用安全,快速的的make_shared和allocate_shared函数。(
boost/make_shared.hpp
)1.3 常用函数
reset()
get()
unique()
swap()
等。
2. make_shared
2.1 生成shared_ptr比new更安全,更高效的方法是make_shared(使用系统默认new操作),allocate_shared(允许用户指定allocate函数)。
2.2 跟new比较
new会有两次内存分配,一次是生成对象( new int() ),一次是引用计数;
make_shared把两次合并成了一次,官方说法是:它可以只用内存分配完成对象分配和相关控制块分配,消除相当一部分创建shared_ptr的开销(Besides convenience and style, such a function is also exception safe and considerably faster because it can use a single allocation for both the object and its corresponding control block, eliminating a significant portion of shared_ptr
's construction overhead.)。
example:
boost::shared_ptr<std::string> x = boost::make_shared<std::string>("hello, world!");std::cout << *x;
3. 综合分析
#include <iostream>#include <boost/make_shared.hpp>#include <thread> typedef std::function<void ()> fp;using namespace std;class Bar{public: Bar() { printf ("Bar init\n"); } void print () { printf ("in the bar \n"); sleep(3); }};int main(){ std::vector<boost::shared_ptr<thread> > kafka_threads; for (int i = 0; i < 2; ++i) { //生成Bar类型shared_ptr,这个时候会创建了Bar对象,调用构造函数; auto kafka_service = boost::make_shared<Bar>(); cout << "push_back thread: " << i << endl; kafka_threads.push_back( //生成新thread,用bind函数绑定Bar成员函数,并作为thread的执行函数,这个时候thread已经开始运行了; boost::make_shared<thread>(std::bind(&Bar::print, kafka_service))); } for (int i = 0; i < 2; ++i) { kafka_threads[i]->join(); }}
0 0
- boost::shared_ptr boost::make_shared
- boost::make_shared
- boost::make_shared
- boost>shared_ptr
- Boost - shared_ptr
- boost>shared_ptr
- boost>shared_ptr
- boost::shared_ptr
- boost::shared_ptr
- boost>shared_ptr
- boost::shared_ptr
- 使用 boost::shared_ptr 时,善用 make_shared 而非 new operator 去动态分配资源
- make_shared && shared_ptr
- about boost::shared_ptr
- boost shared_ptr用法
- boost 中的 shared_ptr
- boost/shared_ptr 用法总结
- boost shared_ptr用法
- 二叉搜索树的序列化和反序列化
- C++卷积神经网络实例:tiny_cnn代码详解(4)——convolutional_layer类结构信息之成员变量与构造函数
- Spring Mvc那点事---(23)Spring Mvc监听器
- iOS 即时通讯XMPP
- Android: Drawable Resources
- boost::shared_ptr boost::make_shared
- 编写一个密码类,其中包含一个 str 密码字符串私有成员数据,一个“==”运算 符重载成员函数,用于比较用户输入的密码是否正确。并用数据测试该类。
- C++卷积神经网络实例:tiny_cnn代码详解(5)——convolutional_layer类结构信息之其他成员函数
- django实现qq一键登录(qq互联)
- Mybatis步步进阶(七)——Mybatis实体关联映射
- 矩阵清零
- C++卷积神经网络实例:tiny_cnn代码详解(6)——average_pooling_layer层结构类分析
- MyEclipse开启后右下角不停的在Update index
- linux常用命令大全