make_shared的CppReference页面说(与make_unique相同)
可能引发std :: bad_alloc或T的构造函数引发的任何异常。如果引发异常,则这些函数无效。
这意味着在失败的情况下可以引发std :: bad_alloc接收。“函数无效”暗含意味着它无法返回nullptr。如果是这种情况,为什么不总是将make_shared / make_unique始终写入try catch块中是一种惯例?
使用make_shared的正确方法是什么?在尝试捕获块内?或检查nullptr?
我从一些博客中读到默认构造的(空)shared_ptr会自动初始化为nullptr. 但是在标准中找不到任何这样的明确声明。
我写了一个小片段(Linux Compiled)来确认这一点:
#include <iostream>
#include <memory>
struct Base;
int main()
{
std::shared_ptr<Base> p;
Base* b;
if (p == nullptr) {
std::cout << "p IS NULL \n";
}
else {
std::cout << "p NOT NULL \n";
}
if (b == nullptr) {
std::cout << "b IS NULL \n";
}
else {
std::cout << "b NOT NULL \n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Run Code Online (Sandbox Code Playgroud)#include <iostream> #include <memory> struct Base; int main() { std::shared_ptr<Base> p; Base* b; …
我目前正在研究std :: condition_variable。在while循环内使用std :: condition_variable :: wait()完全不依赖std :: condition_variable :: notify()是否正确?
每个std :: condition_variable :: wait()都应强制具有std :: condition_variable :: notify()吗?