1

Consider the following code:

#include <memory>

class A {};
class B : public A {};

void func( std::shared_ptr<A> ptr )
{
}

int main( int argc, char* argv[] )
{
    func( std::shared_ptr<A>( new B ) );
}

The syntax std::shared_ptr<A>( new B ) requires A class to be specified. It's a pain if the class is in a namespace and it makes code too verbose when it actually does not need to.

Is there no STL template function that would make the syntax lighter and have A be deduced automatically? I was thinking of something like: func( std::make_shared( new B ) ) but that's not what std::make_shared is meant for.

I mean, there's the same for pair, you can use std::make_pair without having to specify what are the first/second pair types, ther are automatically deduced. Is there not "equivalent" for shared_ptr?

jpo38
  • 20,821
  • 10
  • 70
  • 151

1 Answers1

2

but that's not what std::make_shared is meant for.

On the contrary, this is an ideal use case for std::make_shared:

 func(std::make_shared<B>());

Not only was no need to specify A, but also we have the advantage of the pointed object and the control block having a shared allocation.


Your example has undefined behaviour because the shared pointer would delete the object through pointer to a non-polymorphic base. This make_shared version doesn't have that problem.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • All right, That's just what I was looking for and I was surprised `std::make_shared` did not help...but I was simply not using `make_shared`correctly! – jpo38 Dec 16 '20 at 10:52