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?
Asked
Active
Viewed 2,929 times
3
-
https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared <-- no. The thing throws an exception, er returns a valid shared pointer. – Marcus Müller Apr 08 '20 at 07:54
-
Assuming a conformant Implementation, no. If you're really paranoid, add a cassert `assert` that will get optimized out in release builds. – Qix - MONICA WAS MISTREATED Apr 08 '20 at 07:56
1 Answers
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