【发布时间】:2016-09-27 15:00:04
【问题描述】:
与new 运算符相比,使用std::make_unique 初始化std::unique_ptr 有哪些优势?
换句话说,为什么是
std::unique_ptr<SomeObject> a = std::make_unique(SomeObject(...))
比做更好
std::unique_ptr<SomeObject> a = new SomeObject(...)
我尝试在网上查了很多资料,我知道在现代 C++ 中避免使用运算符 new 是一个很好的经验法则,但我不确定在这种确切情况下有什么优势。它是否可以防止任何可能发生的内存泄漏?使用std::make_unique 是否比使用new 更快?
【问题讨论】:
-
其实
std::make_unique(SomeObject(...))导致调用构造函数和复制/移动构造函数。当然,更好的选择是直接使用底层模板类型的构造函数参数调用std::make_unique。
标签: c++ c++14 unique-ptr