#include<iostream> #include <new> using namespace std; int main() { /** * 动态内存 * url: http://www.cplusplus.com/doc/tutorial/dynamic/ * 关键字new用于在程序运行时动态开辟内存,内存开辟在堆空间. * 此关键字不保证内存一定开辟成功,如果开辟失败,抛出bad_alloc异常,如果此异常没有指定的异常handle,程序就会终止. */ int * foo = nullptr; foo = new int[5]; // if allocation fails, an exception is thrown //另一个方法是nothrow,使用此方法,内存开辟失败,返回null,而不是抛出异常让程序终止 //此方法声明在new文件头内 foo = new (std::nothrow) int[5]; if(foo == nullptr) { } else { foo[0] = 1; cout << foo[0] << endl; delete[] foo; } //内存不在使用,删除内存,delete int i, n; int *p; cout << "how many numbers would you like to type?\n"; cin >> i; cout << "i=" << i << endl; p = new (std::nothrow) int[i]; if(p == nullptr) { cout << "Error: memory could not be allocated" << endl; } else { for(n = 0; n < i; n++) { cout << "enter number:"; cin >> p[n]; } cout << "you have enter:"; for(n = 0; n < i; n++) cout << p[n] << ", "; delete[] p; } return 0; }