Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 888
Alex Lee Avatar asked Nov 16 '25 16:11

Alex Lee


1 Answers

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.

like image 130
NutCracker Avatar answered Nov 18 '25 05:11

NutCracker