Why std::unique_ptr does not permit type inference

2020-02-28 02:32发布

All is in the title. It would be easier to read/write the second line of my example since the type of the template argument is obvious:

#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());
}

Of course, if you want to use polymorphism, we could always write:

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

What is the reason of such a constraint?

1条回答
混吃等死
2楼-- · 2020-02-28 03:12

This is not an issue that's... unique to 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 exist: they use template function argument deduction to reduce boilerplate.


In C++17 you will be able to write:

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

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

The deduction guide is required because std::unique_ptr's constructor that takes a raw pointer uses the pointer type alias which is defined as follows:

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

Type aliases like pointer are non-deducible contexts, so P0433R0 proposes the addition of:

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>;  

Which would enable class template deduction for std::unique_ptr.

查看更多
登录 后发表回答