C++ Logo


Advanced search

Re: std::make_shared and type deduction

From: Andrew Schepler <aschepler_at_[hidden]>
Date: Tue, 7 Jul 2020 17:59:24 -0400
On Tue, Jul 7, 2020 at 2:37 PM Kyle Knoepfel via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> ... it is easy enough to create a wrapper function that does the type
> deduction for you:
> template <typename T>
> auto as_unique_ptr(T&& t) { return
> std::make_unique<T>(std::forward<T>(t)); }
> auto foo_ptr = as_unique_ptr(external_library::make_foo());
> or something similar.
> The question: when developing std::make_(shared|unique), was it ever
> envisaged that an extension (perhaps a differently named facility) could
> exist that would type-deduce T as in the above as_unique_ptr function?
> Looking at the proposal for std::make_shared (
> http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2007/n2232.html) I saw
> no mention of it.

I'd just note that make_unique<T> and make_shared<T> do more than just take
a T value as argument. They take any arguments which are valid for a public
constructor of T. If you want, you can pass a T object to use the move or
copy constructor. So we're talking about a convenience function for a
specific case (and I would definitely use a different name). If that was
already obvious to everyone, sorry, and carry on.

And a small correction to your as_unique_ptr: I think you want return
std::unique_ptr<std::remove_cvref_t<T>>, to avoid an lvalue causing an
invalid attempt to instantiate unique_ptr<type&>.

-- Andrew Schepler

Received on 2020-07-07 17:02:52