C++动态内存最佳实践
C++ Dynamic Memory Best Practice
我正在学习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_unique
或std::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);
}
}
相关文章:
- 删除类成员的动态分配内存的最佳方法是什么
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 组织从内存读取的数据的最佳方法(用于调试)c++
- C++动态内存最佳实践
- 如何使商店成为内存的开始和结束,以获得最佳拟合
- 读取内存值(实时)最佳实践
- 在C/C 中实现实时最佳拟合内存分配算法
- ifstream是在不使用内存的情况下进行读取的最佳方式
- 读取文本文件而不占用内存的最佳方式
- 在静态函数中释放内存的最佳方式
- 将图形存储到内存中的最佳方式
- API 设计是告诉 API 的使用者分配内存的最佳做法
- 将全局复制到共享内存的最佳方法
- C++容器:最佳内存管理
- 在构造函数中引发异常时防止内存泄漏的最佳做法是什么?
- 查找内存泄漏的最佳解决方案
- 包装总库的最佳实践内存管理
- 使用智能指针进行手动内存管理的最佳策略
- 分配大内存的最佳方式
- 为什么Visual Studio没有优化结构体以获得最佳内存使用?