程序編譯通過,執行結果如下:
D::D()
terminate called after throwing an instance of 'boost::exception_detail::clone_impl >'
what(): tr1::bad_weak_ptr
Aborted
說明在D的構造函數中調用shared_from_this(), 此時D的實例本身尚未構造成功,weak_ptr也就尚未設置,所以程序拋出tr1::bad_weak_ptr異常。
錯誤的使用代碼二:
程序編譯通過,執行結果如下:
D::D()
D::func()
terminate called after throwing an instance of 'boost::exception_detail::clone_impl >'
what(): tr1::bad_weak_ptr
Aborted
失敗原因分析:
在主函數main中,D的實例是在棧上構造,沒有使用boost::shared_ptr 的構造方式,
所以boost::enable_shared_from_this中的weak_ptr所指的函數對象也就沒有被賦值,
在調用d.func()中使用shared_from_this()函數時
----注:shared_from_this的函數實現 ------
shared_ptr shared_from_this()
{
shared_ptr p( weak_this_ );
BOOST_ASSERT( p.get() == this );
return p;
}
----注:shared_from_this的函數實現 ------
調用BOOST_ASSERT( p.get() == this ); 失敗,拋出以上異常。
最后,我們給出share_from_this()的正確使用例子: