C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: std::make_shared and type deduction
From: Andrew Schepler (aschepler_at_[hidden])
Date: 2020-07-07 16:59:24


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



STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups