Search code examples
c++c++11shared-ptr

How to create a shared_ptr concisely?


How to make the statement shorter:

auto ptr = std::shared_ptr<CPoint>(new CPoint(x, y));

Please notice the CPoint appears twice. Can it be shorter?

like:

auto ptr = XXXX<CPoint>(x, y);

XXXX is a macro or anything. It should apply to any constructor with any parameters.

auto ptrA = XXXX<ClassA>(); // a shared_ptr to new ClassA()
auto ptrB = XXXX<ClassB>(a, b, c); // a shared_ptr to new ClassB(a, b, c)

Solution

  • You could, and should, use function template std::make_shared:

    auto p = std::make_shared<CPoint>(x, y);
    auto pA = std::make_shared<ClassA>(); // a shared_ptr to new ClassA()
    auto pB = std::make_shared<ClassB>(a, b, c); // a shared_ptr to new ClassB(a, b, c)
    

    To give it a different name, you can use a simple wrapper function:

    template< class T, class... Args>
    std::shared_ptr<T> foo( Args&&... args )
    {
      return std::make_shared<T>( std::forward<Args>(args)...);
    }
    

    then

    auto pB = foo<ClassB>(a, b, c);