std :: make_unique可以和抽象接口一起使用吗?

Bor*_*ris 10 c++ std unique-ptr

考虑以下代码行:

auto source1 = std::unique_ptr<IGpsSource>(new GpsDevice(comPort, baudrate));
auto source2 = std::unique_ptr<IGpsSource>(new GpsLog(filename));
Run Code Online (Sandbox Code Playgroud)

如何使用VS 2013支持的新std :: make_unique函数编写?它甚至可能吗?*

*我的问题是我不知道怎么告诉'make_unique'要实例化什么样的对象.因为只传递了构造函数的参数,所以似乎无法控制...

Rei*_*ica 16

是的,你当然可以使用make_unique它,但它没有你想要的那么有用.你有这些选择:

std::unique_ptr<IGpsSource> source1 = std::make_unique<GpsDevice>(comPort, baudrate);
auto source2 = std::unique_ptr<IGpsSource>{ std::make_unique<GpsLog>(filename) };
Run Code Online (Sandbox Code Playgroud)

我会说真正的问题是"你为什么要那样?"

  1. 不同make_shared,make_unique没有分配好处new.因此,如果您需要控制指针的类型,那么您正在做的就好了.

  2. 为什么首先需要输入指针IGpsSource?存在从std::unique_ptr<Derived> rvaluesstd::unique_ptr<Base>rvalues 的隐式转换.因此,如果您实际上正在调用make_unique初始化IGpsSource指针,它将正常工作.如果你想将指针转移到某个地方,std::move无论如何你都必须这样做,此时转换可以再次发生.

  • 异常安全论点[来自这个答案](http://stackoverflow.com/a/20895705/673852)仍然适用于`make_unique`,不仅适用于`make_shared`.因此,`make_unique <Xyz>()`应优先于`unique_ptr(new Xyz)`. (5认同)

Ajm*_*mal 10

std::unique_ptr<Base> base_ptr = std::make_unique<Derived>();
Run Code Online (Sandbox Code Playgroud)

正如Angew所说,上述情况应该可以正常进行.提供 Derived使用公共继承.只是想为了完整性而添加它.