C++ std::make_shared


不要這樣使用智能指針:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM