1、可能有的人涉及到动态分配只用到下面的这句:
#include <iostream>
using namespace std;
int main(void)
{
int *p;
p = new int(1); // 1
cout << *p << endl;
int *q;
q = (int *)malloc(sizeof(int));
*q = 1;
cout << *q << endl;
return 0;
}
漏洞百出,不想多说。
(补充一句,上面用的是new的plain new用法)
2、自己总结了一下动态分配的写法(当然还有其他写法),以后就这么写了:
#include <iostream>
using namespace std;
int main(void)
{
int *p = NULL;
p = new(nothrow) int(1); // 1
if (p == NULL) { // 2
cerr << "Allocate failed!" << endl;
exit(OVERFLOW);
}
cout << *p << endl;
delete p; // 3
p = NULL; // 4
/*----------------------------------------------------*/
int *q = NULL;
q = (int *)malloc(sizeof(int)); // 1
if (q == NULL) { // 2
cerr << "Allocate failed!" << endl;
exit(OVERFLOW);
}
*q = 1;
cout << *q << endl;
free(q); // 3
q = NULL; // 4
return 0;
}
扩展阅读:林锐
http://blog.sina.com.cn/s/blog_446b43c10100d7ci.html
2012/8/10
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
http://www.cplusplus.com/doc/tutorial/dynamic/