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

Is it possible that make_shared has no any exception but returns a nullptr?


I am recently dealing with a problem with shared_ptr. I am curious if make_shared failed, it will raise exceptions right? Is there any kind of situation that the make_shared returned a nullptr but without any exceptions?


Solution

  • From the docs:

    std::make_shared ...

    May throw std::bad_alloc or any exception thrown by the constructor of T.

    So, if you throw exception from your class' constructor, then std::make_shared will throw it too. Besides exceptions thrown from constructor, std::make_shared could throw std::bad_alloc exception on its own.

    Therefore, you don't need to check if the result of std::make_shared is nullptr. Just be sure to catch the exception and properly handle it.