C++动态内存最佳实践

C++ Dynamic Memory Best Practice

本文关键字:最佳 内存 动态 C++      更新时间:2023-10-16

我正在学习C++,我遇到了一些代码,我对它到底做了什么感到困惑。我正在学习动态记忆,我学习它的地方提到这是很好的做法。

double * pvalue = NULL;
if(!(pvalue = new double)){
  cout<<"Error: out of memory." << endl;
  exit(1);
}

我知道您正在创建一个名为 pvalue 的指针,但我不明白 if 语句。如果有人能向我解释,我将不胜感激。

我对它到底做了什么感到困惑。

使用非常过时的概念和对C++的有限理解。

首先,C++不会通过返回 NULL 来报告分配内存失败。它抛出类型为 std::bad_alloc 的异常(派生自 std::exception (。

其次,随着 C++11 的出现,使用这样的"裸"指针是不受欢迎的,因为当您忘记delete它们时,它们很容易导致资源泄漏,例如,当意外异常使您的指针超出范围时。

所以你真的应该使用 std::shared_ptr<> 或 unique_ptr<>。

     pvalue = new double   // This allocates a dynamic double as usual
   !(pvalue = new double)  // This takes the value of the resulting pointer
                           // and negates it, checking whether it's null
if(!(pvalue = new double)) // It all becomes the condition for the if.

值得注意的是:

  • 原始拥有指针不得在C++中使用,而应使用智能指针;
  • 不得使用using namespace std;(我确信此示例具有(;
  • 动态分配单个double奇怪;
  • new永远不会返回空指针,因此检查毫无意义;
  • std::exit会在飞行途中核弹,泄漏所有具有自动生存期的对象,而是从main返回。

[...]我正在学习它的地方提到这是很好的做法。

是时候戴上一些重金属和太阳镜,放火烧"这个地方",去寻找一些更好的学习材料。

这个:

if(!(pvalue = new double)){

。只是一种(也许也是(聪明的速记方式:

pvalue = new double;
if (pvalue == NULL) {...}
除非您

提供std::nothrow,否则new永远不会返回nullptr。相反,如果new失败,它将抛出std::bad_alloc

更合适的解决方案是:

#include <iostream>
#include <stdexcept>
double * foo()
{
    double * pvalue = nullptr;
    try {
        pvalue = new double;
    }
    catch(const std::bad_alloc &)   {
        std::cout << "Error: out of memory." << std::endl;
        exit(1);
    }
    return pvalue;
}

但是,不鼓励在现代代码中使用原始拥有指针。 通常避免new,而赞成std::make_uniquestd::make_shared。例如,更好的解决方案是这样的:

#include <iostream>
#include <memory>
#include <stdexcept>
std::unique_ptr<double> foo()
{
    try {
        return std::make_unique<double>();
    }
    catch(const std::bad_alloc &)   {
        std::cout << "Error: out of memory." << std::endl;
        exit(1);
    }
}