C++ Logo


Advanced search

Re: std::make_shared and type deduction

From: Kyle Knoepfel <kyleknoepfel_at_[hidden]>
Date: Wed, 8 Jul 2020 14:29:27 -0500
> On Tuesday, 7 July 2020 11:37:03 PDT Kyle Knoepfel via Std-Discussion wrote:
> > I routinely encounter situations where objects must be owned by (smart)
> > pointer, but the means in which the pointee is constructed is not under my
> > control. For example:
> >
> > namespace external_library {
> > template <typename T>
> > Foo<T> make_foo();
> > }
> This is not a good example because make_foo did not return a pointer. It
> returned an object by value. Therefore, when you do:
> > auto foo_ptr = std::make_unique<Foo<int>>(external_library::make_foo());
> The pointee is constructed fully in your control. You're creating a copy of
> Foo<int> and saving that in a unique_ptr.
> But note how Foo<int> can be copied. So are you sure you need unique_ptr in
> the first place?
Without showing how foo_ptr is used, I agree it's not clear why this particular example is all that persuasive. In the use case I have in mind, foo_ptr is handed off to a framework which then encapsulates it in a class used for data-handling and persisting objects to disk. A combination of templating and inheritance makes this possible, all predicated on the necessity of using a unique_ptr.

The interface is something like:

framework.store(move(foo_ptr)); // or

Ideally, either make_foo would change its interface, or framework::store would change its interface--but I don't necessarily have control over either.


Received on 2020-07-08 14:32:43