enable_from_this方法的使用與陷阱
enable_from_this 的使用與實現(xiàn)原理說明:
shared_from_this()是enable_shared_from_this的成員函數(shù),返回shared_ptr;
注意的是,這個函數(shù)僅在shared_ptr的構(gòu)造函數(shù)被調(diào)用之后才能使用。
原因是enable_shared_from_this::weak_ptr并不在構(gòu)造函數(shù)中設(shè)置,而是在shared_ptr的構(gòu)造函數(shù)中設(shè)置。
錯誤的使用代碼一:
程序編譯通過,執(zhí)行結(jié)果如下:
D::D()
terminate called after throwing an instance of 'boost::exception_detail::clone_impl >'
what(): tr1::bad_weak_ptr
Aborted
說明在D的構(gòu)造函數(shù)中調(diào)用shared_from_this(), 此時D的實例本身尚未構(gòu)造成功,weak_ptr也就尚未設(shè)置,所以程序拋出tr1::bad_weak_ptr異常。
錯誤的使用代碼二:
程序編譯通過,執(zhí)行結(jié)果如下:
D::D()
D::func()
terminate called after throwing an instance of 'boost::exception_detail::clone_impl >'
what(): tr1::bad_weak_ptr
Aborted
失敗原因分析:
在主函數(shù)main中,D的實例是在棧上構(gòu)造,沒有使用boost::shared_ptr 的構(gòu)造方式,
所以boost::enable_shared_from_this中的weak_ptr所指的函數(shù)對象也就沒有被賦值,
在調(diào)用d.func()中使用shared_from_this()函數(shù)時
----注:shared_from_this的函數(shù)實現(xiàn) ------
shared_ptr shared_from_this()
{
shared_ptr p( weak_this_ );
BOOST_ASSERT( p.get() == this );
return p;
}
----注:shared_from_this的函數(shù)實現(xiàn) ------
調(diào)用BOOST_ASSERT( p.get() == this ); 失敗,拋出以上異常。
最后,我們給出share_from_this()的正確使用例子: