什么是使用的优势,std::make_unique在new运营商的初始化std::unique_ptr?
换句话说,为什么
std::unique_ptr<SomeObject> a = std::make_unique(SomeObject(...))
Run Code Online (Sandbox Code Playgroud)
比做好
std::unique_ptr<SomeObject> a = new SomeObject(...)
Run Code Online (Sandbox Code Playgroud)
我尝试在线查看很多,我知道new在现代C++中避免使用操作符是一个很好的经验法则,但我不确定在这个确切的场景中有什么优势.它是否可以防止可能发生的任何类型的内存泄漏?做一个std::make_unique比使用更快new吗?
假设我有处理基类和派生类的工厂函数:
#include <memory>
using namespace std;
struct B { virtual ~B() {} };
struct D : B {};
unique_ptr<B> MakeB()
{
auto b = unique_ptr<B>( new B() );
return b; // Ok!
}
unique_ptr<B> MakeD()
{
auto d = unique_ptr<D>( new D() );
return d; // Doh!
}
Run Code Online (Sandbox Code Playgroud)
在上面的最后一行,我需要move(d)为了使它工作,否则我得到"错误:无效转换std::unique_ptr<D>为std::unique_ptr<D>&&." 我的直觉说,在这种情况下,编译器应该知道它可以隐式地创建d一个rvalue并将其移动到基指针中,但事实并非如此.
这在我的编译器(gcc 4.8.1和VS2012)中是不可靠的吗?预期的设计unique_ptr?标准有缺陷吗?
我知道派生类unique_ptr可能发生在unique_ptr多态类型需要基类的地方.例如,从函数返回时
unique_ptr<Base> someFunction()
{
return make_unique<Derived>(new Derived());
}
Run Code Online (Sandbox Code Playgroud)
或传递给函数作为参数.
// Function taking unique pointer
void someOtherFunction(unique_ptr<Base>&& ptr)
// Code calling this function
someOtherFunction(std::move(ptrToDerived));
Run Code Online (Sandbox Code Playgroud)
我的问题是:这种向上转换是否总是自动的?或者我们需要使用明确执行它dynamic_cast吗?