c++template-classes

How to understand `std::make_shared<Object>("foo")`?


What does std::make_shared<Object>("foo") do?

std::shared_ptr<Object> p1 = std::make_shared<Object>("foo");

I know that std::make_shared<T> is template class and I could understand Object("foo") is a temporary object indeed. But I could not understand std::make_shared<Object>("foo").

Can someone explain me, step by step, sequence of objects created and operations done by it?


Solution

  • std::make_shared<Object>("foo")
    

    method

    Notice the std::make_shared at the start of this code. It identifies a function. If we put the actual function aside and step back a little, then before the <> signs and the () sign you have a function name.

    generic

    The in this code specifies that the generic T is specified in this case to be Object. It's not a good idea to think of it as if it was a temporary object. It's a specification.

    the call

    ("foo") is ensuring that the function is called and a parameter is passed to it.

    bottom line

    The documentation is providing you a proper description of this:

    enter image description here

    It tells you that the constructor of the given type specified (Object in this case) will be instantiated and will be wrapped in a shared_ptr.