设为首页 加入收藏

TOP

c++ 11学习笔记--智能指针(二)
2015-07-20 18:01:19 来源: 作者: 【 】 浏览:12
Tags:学习 笔记 智能 指针
->getptr();
? ? std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
} // UB: double-delete of Bad
复制代码
1.绝对不能在构造函数中调用shared_from_this()
?
因为shared_ptr里面初始化enable_shared_from_this的成员weak_ptr, ? ? ?这个时候weak_ptr还是空值。
?
??
?
2.为什么内部不能用this指针
?
因为我们程序中用shared_ptr来管理指针,如果我们在类的内部传递的过程中用原始指针,这样类内部的引用shared_ptr不会察觉到,因为有可能我们传进去的时候已经被shared_ptr释放掉了。
?
?
?
unique_ptr
?
相对就要单纯许多了,unique_ptr“唯一”拥有其所指对象,只能有一个unique_ptr指向给定对象(通过禁止拷贝语义、只有移动语义来实现)。
?
?
?
代替普通指针
?
复制代码
void foo() ?
{//不安全的代码 ?
? ? X *px = new X; ?
? ? // do something, exception may occurs ?
delete px; // may not go here ? ??
?
}?
?
unique_ptr px(new X); ?
复制代码
在函数中返回对象
?
?
?
unique_ptr foo() ?
{ ?
? ? unique_ptr px(new X); ?
? ? // do something ?
? ? return px; //移动语义 ?
} ?
放入容器中
?
vector> vs { new string{“1111”}, new string{“2222”},new string{“3333”} ?}; ?
?
vector>v; ?
unique_ptr test(new string("11111")); ?
v.push_back(std::move(test));//使用移动语法
支持直接持有数组
?
std::shared_ptr p(new int[10],
? ? [](int* p){
? ? ? ? delete[] p;
? ? });
//或者使用helper
std::shared_ptr p(new int[10],std::default_delete());
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇泛型编程与C++标准模板库 : 浅谈s.. 下一篇codeforces #259 DIV2 C题 Little..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: