了解 C++ 中动态内存分配的使用
understanding the use of dynamic memory allocation in c++
>请考虑此程序:
#include <iostream>
using namespace std;
int main ()
{
int i;
cout << "How many numbers would you like to type? ";
cin >> i;
int * p;
p= new int[i];
cout << "Enter the numbers: n";
for (int n=0; n<i; n++)
cin >> p[n];
cout << "You have entered: ";
for (int n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
return 0;
}
而这个:
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "How many numbers would you like to type? ";
cin >> num;
int arr[num];
cout << "Enter the numbers: n";
for (int a = 0; a <num; ++a)
cin >>arr[a];
cout << "You have entered: ";
for (int a = 0; a <num; ++a)
cout <<arr[a]<< ", ";
return 0;
}
这两个程序都在完成相同的任务,对我来说,后者很多
比前者更容易理解。现在我的问题是为什么我们需要动态内存分配?
当num
不是编译器时间常数时,int arr[num];
是VLA(可变长度数组),这不是标准C++。这是一些编译器提供的语言扩展(我假设您使用的是 G++)。
std::vector
一些易于使用且不需要您使用原始指针和处理手动动态分配的东西是
int i;
cout << "How many numbers would you like to type? ";
if (!(cin >> i)) { // error checking is important
cout << "Not a number, abort!n";
return 1;
}
std::vector<int> numbers(i);
cout << "Enter the numbers: n";
for (int a = 0; a < i; ++a)
cin >> numbers[a];
考虑一下,如果您创建的这个数组需要存活超过创建它的函数的范围,会发生什么情况。例如,如果这不是 main()
函数,而是将内存返回到 main 的某个帮助程序函数。或者,也许您无法提前知道要创建多少对象。例如,您可以基于动态实时数据维护基于树或图形的数据结构。
在您给出的简单示例中,您是对的:在堆上动态分配数组可能是一种浪费,如果做得不好,很容易导致内存泄漏等问题(尽管有一些解决方法,例如使用现代 RAII 技术进行所有分配)。但是,如果动态内存可用,则更复杂的方案会变得简单得多。
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?