不要這樣使用智能指針:
foo( std::shared_ptr<int>(new int), bar() );
原因在於表達式求值的順序,絕非想想的那樣簡單。參考:https://blog.csdn.net/ox_thedarkness/article/details/613122
可能是先new int, 然后調用bar(), 當bar()拋異常時,智能指針還未接管heap上的int對象。
解決方法1)
std::shared_ptr<int> sp(new int); foo( sp , bar() );
是不是非常繁瑣?現在有了make_shared
foo(std::make_shared<int>(), bar());
參考:https://github.com/AnthonyCalandra/modern-cpp-features