3

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?

NutCracker
  • 11,485
  • 4
  • 44
  • 68
Alex Lee
  • 309
  • 3
  • 11

1 Answers1

8

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.

NutCracker
  • 11,485
  • 4
  • 44
  • 68