weak_ptr
weak_ptr是爲了配合shared_ptr而引入的一種智能指針,它更像是 shared_ptr的一個助手而不是智能指針,它不具有普通指針的行爲,沒有重載operator* 和->。
用法:
#include <iostream>
#include <string>
#include <vector>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;
int main()
{
boost::shared_ptr<int> sp(new int(10));
assert(sp.use_count() == 1);
//從shared_ptr創建weak_ptr,weak_ptr不影響引用計數
boost::weak_ptr<int> wp(sp);
assert(wp.use_count() == 1);
if (!wp.expired())
{
//獲得一個shared_ptr
boost::shared_ptr<int> sp2 = wp.lock();
*sp2 = 100;
assert(wp.use_count() == 2);
}//退出作用域,sp2自動析構,引用計數減1
assert(wp.use_count() == 1);
//shared_ptr失效
sp.reset();
assert(wp.expired());
//weak_ptr將獲得一個空指針
assert(!wp.lock());
getchar();
return 0;
}
enable_shared_from_this
weak_ptr的一個重要用途是獲得this指針的shared_ptr,使對象自己能夠生shared_ptr管理自己。
在頭文件<boost/enable_shared_from_this.hpp>定義了一個助手類enable_shared_from_this<T>,它的聲明如下:
template<class T>
class enable_shared_from_this
{
public:
shared_ptr<T> shared_from_this();
}
使用的時候只需要讓想被shared_ptr管理的類從它派生即可,成員函數shared_from_this()會返回this的shared_ptr。
#include <iostream>
#include <string>
#include <vector>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost;
class self_shared : public enable_shared_from_this<self_shared>
{
public:
self_shared(int n) : x(n) {}
int x;
void print()
{
std::cout << "self_shared:" << x << std::endl;
}
};
int main()
{
auto sp = make_shared<self_shared>(333);
sp->print();
auto p = sp->shared_from_this();
p->x = 1000;
p->print();
getchar();
return 0;
}
enable_shared_from_raw
與上面類似,它不要求對象必須被一個shared_ptr管理,可以直接從一個原始指針創建出shared_ptr。
enable_shared_from_raw利用了shared_ptr別名構造函數特性,內部持有一個void*空指針shared_ptr作爲引用的觀察者,從而達到管理原始指針的目的。
注意:調用shared_from_raw()後,由於存在shared_ptr成員變量的原因,對象內部會有一個shared_ptr的強引用,所以即使其他的shared_ptr都析構了原始指針也不會被自動刪除。
#include <iostream>
#include <string>
#include <vector>
#include <boost/smart_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/smart_ptr/enable_shared_from_raw.hpp>
using namespace boost;
class row_shared : public enable_shared_from_raw
{
public:
row_shared()
{
std::cout << "row_shared ctor" <<std::endl;
}
~row_shared()
{
std::cout << "row_shared dtor" << std::endl;
}
};
int main()
{
row_shared x;
//此時無引用,注意用&取地址
assert(!weak_from_raw(&x).use_count());
//獲取shared_ptr
auto px = shared_from_raw(&x);
//引用計數爲2
assert(px.use_count() == 2);
getchar();
return 0;
}