C++ Logo

std-discussion

Advanced search

Re: std::make_shared and type deduction

From: Kyle Knoepfel <kyleknoepfel_at_[hidden]>
Date: Wed, 8 Jul 2020 13:35:59 -0500
> On Jul 7, 2020, at 4:59 PM, Andrew Schepler <aschepler_at_[hidden]> wrote:
>
> On Tue, Jul 7, 2020 at 2:37 PM Kyle Knoepfel via Std-Discussion <std-discussion_at_[hidden] <mailto: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 <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).

Precisely. So sure, I can image a convenience function that achieves the above. I'm wondering, though, if there was a reason why such a utility was not originally proposed in 2007. Too specific of a use case, maybe? Would a proposal for such a convenience function even be worth consideration, now that we're 13 years after the std::make_shared proposal?

> 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&>.

Good catch, and thanks,
Kyle


Received on 2020-07-08 13:39:19