为什么 std::unique_ptr 不允许类型推断?

Why does std::unique_ptr not permit type inference?

read/write 我示例的第二行会更容易,因为模板参数的类型很明显:

#include <memory>

struct Foo{};

int main()
{
  // redundant: good
  auto foo1 = std::unique_ptr<Foo>(new Foo());
  // without explicitness: does not compile
  auto foo2 = std::unique_ptr(new Foo());
}

当然,如果你想使用多态,我们可以这样写:

auto base = std::unique_ptr<Base>(new Derived());

这样限制的原因是什么?

这不是 std::unique_ptr - instantiation of template classes does not automatically deduce the types from the constructors previous to C++17. This is why facilities such as std::make_unique, std::make_pair and std::make_tuple 独有的问题:他们使用 模板函数参数推导 来减少样板文件。


在 C++17 中,您将能够编写:

auto foo2 = std::unique_ptr(new Foo());

感谢 class template deduction - assuming P0433R0 is accepted, which adds a deduction guide to std::unique_ptr

推导指南是必需的,因为std::unique_ptr's constructor that takes a raw pointer使用了定义如下的pointer类型别名:

std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*. Must satisfy NullablePointer.

pointer这样的类型别名是不可推导的上下文,因此P0433R0建议添加:

template<class T> unique_ptr(T*) 
    -> unique_ptr<T, default_delete<T>>;

template<class T, class V> unique_ptr(T*, V) 
    -> unique_ptr<T, default_delete<T, V>>;  

template<class U, class V> unique_ptr(U, V) 
    -> unique_ptr<typename pointer_traits<typename V::pointer>::element_type, V>;  

这将为 std::unique_ptr.

启用 class 模板推导

没有推导指南的真正原因是:

There is no class template argument deduction from pointer type because it is impossible to distinguish a pointer obtained from array and non-array forms of new

旁注:另一个答案承诺 c++17 将允许编译:

根本不是这样的。也是因为上面的原因。