【发布时间】:2018-11-29 12:39:08
【问题描述】:
考虑以下智能指针std::unique_ptr的用法:
std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
如何检查new 是否成功?
我有两个选择:
- 方法 1 - 检查布尔值:
if(!sp){} - 方法 2 - 与空指针比较:
if(sp==nullptr){}
示例 (source)
#include <iostream>
#include <memory>
using namespace std;
int main() {
constexpr long long sz = 1000000e10;
//raw pointer
auto ptr = new(std::nothrow) char[sz];
if(ptr==nullptr)
{
cout<<"ptr nullptr"<<endl;
}
//smart pointer
std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
if(!sp)
{
cout<<"sp nullptr bool"<<endl;
}
if(sp==nullptr)
{
cout<<"sp nullptr =="<<endl;
}
return 0;
}
输出:
Success #stdin #stdout 0s 4396KB
ptr nullptr
sp nullptr bool
sp nullptr ==
显然,方法 1 和方法 2 似乎都有效。
不过,我想从权威来源(C++ 标准、msdn、gcc 文档)中了解到这确实是正确的方法。
【问题讨论】:
-
800 个代表,但您仍然不知道您不应该发布 图像 的代码?
-
我无法格式化它。这是我第一次在stackoverflow中遇到这样的格式问题。因此,我还添加了指向 ideone 的链接。
-
@SahilSingh 从你的问题来看,你似乎不知道。如果你想让这两种方法做同样的事情,第一个应该是
if (!sp)。 -
在这一点上,这个问题肯定不像之前得到的反对票那么糟糕,但我怀疑有人会撤销他们的反对票:-(
-
@einpoklum 1001 个第一次解决问题的理由......如果一个问题浪费了人们的时间,即使它稍后得到解决,它仍然是在浪费他们的时间。如果这是一个很好的问题,它稍后会被其他人投票,最终可能会得到净正面
标签: c++ c++11 new-operator smart-pointers unique-ptr