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