我试图理解 C++ 中的内存部分。我试图在使用下面的代码生成输出后释放内存。
问题:
是否需要使用 if 语句来释放内存?
代码:
int main(){
char *pc;
int *pi;
pc = new char('a');
pi = new int(8);
cout << *pc << endl;
cout << *pi << endl;
//What's the purpose for doing if(pc) and if (pi) below?
if(pc){
delete pc;
}
if(pi){
delete pi;
}
return 0;
}
我可以这样做吗?int main(){ 字符 *pc; 整数 *pi;
pc = new char('a');
pi = new int(8);
cout << *pc << endl;
cout << *pi << endl;
delete pc;
delete pi;
return 0;
}