【问题标题】:How to check if C++ smart pointer memory allocation was successful?如何检查 C++ 智能指针内存分配是否成功?
【发布时间】:2018-11-29 12:39:08
【问题描述】:

考虑以下智能指针std::unique_ptr的用法:

std::unique_ptr<char> sp(new(std::nothrow) char[sz]);

如何检查new 是否成功?

我有两个选择:

  1. 方法 1 - 检查布尔值:if(!sp){}
  2. 方法 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


【解决方案1】:

我作为权威人士,可以确认这两种方式确实都是正确的。

开个玩笑:std::unique_ptroperator ==(std::nullptr_t)operator bool 被重载以执行您对指针的期望,所以是的,两者都是正确的,尽管方法 1 更惯用。

【讨论】:

  • 哈!作为权威来源。我希望您的回答能够让这个搁置的帖子转机。 :) +1
猜你喜欢
  • 2010-12-07
  • 2011-03-05
  • 2019-03-09
  • 2016-08-20
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2016-08-25
  • 2015-10-05
相关资源
最近更新 更多