c++ - Need to check for nullptr when make_shared and make_unique is used?
问题描述
If I am creating a pointer using make_shared
or make_unique
do I ever have to check whether it is nullptr
or not, like:
std::unique_ptr<class> p = std::make_unique<class>();
if (p == nullptr)
{
....
....
}
If you’re really running out of memory, std::make_unique
will through an expection. So you will never get a null pointer from std::make_unique
.
Is this correct ?
So there's no need to check for nullptr
when you do make_shared
and make_unique
?
解决方案
从 cppreference 开始std::make_unique
(类似于std::make_shared
):
例外
可能会抛出
std::bad_alloc
或由 的构造函数抛出的任何异常T
。如果抛出异常,则此函数无效。
“这个函数没有效果”具体意味着它不返回任何东西,因为异常处理机制启动了。所以是的,你的假设是正确的。错误处理std::make_unique
是由异常完成的,返回值是 never nullptr
。
推荐阅读
- c# - 为 webBrowser_.DocumentCompleted 创建多个处理程序
- python - Python 多处理:将任务异步分配给管理器
- ios - 无法在 iOS 上的 Azure NotificationHub 中注册设备,没有回调
- php - 如何根据另一个表的过滤器从一个表中快速返回和计算行数
- c# - 正则表达式用 Postgresql LIMIT 语法转换 Sql Server TOP 语法
- python - Avoiding For Loops / Iterating over two tables
- spring - How to send complex model with files in flutter via chopper to spring
- python - 如何替换单个字符而不影响字符在整个单词中的出现?
- c++ - I find myself lost in this error message on hackerRank's function task
- xcode - Anyone Know How to Switch butttons with Keyboard without use the Mouse on Mac?