// allocate and initialize a const object
const int *pci = new const int(222); // initialize to 222
const int *pci2 = new const int(); // initialize to 0
尽管程序员不能改变 const 对象的值,但可撤销对象本身。
delete pci; // ok: delete a const object
三种常见的程序错误都与动态内存分配相关:
1、删除动态分配内存失败,称为内存泄漏(memory leak)
2、读写已删除的对象
3、对同一个内存空间使用两次 delete 表达式。当两个指针指向同一个动态创建的对象,删除时就会发生错误。第二个指针的 delete 操作往往会破坏自由存储区。
个人实践部分:
#include <iostream>
#include <cstring>
using namespace std;
int main(void)
{
string str = "hello str";
// strNew points to dynamically allocated,
// initialized to empty string
string *strNew = new string;
cout<<"str object address: "<<&str<<endl;
cout<<"strNew pointer itself address: "<<&strNew<<endl;
cout<<"strNew pointer to address: "<<strNew<<endl;
// assignment
*strNew = "hello strNew";
cout<<"strNew pointer to address: "<<strNew<<endl;
// free memory
delete strNew;
cout<<"strNew pointer to address: "<<strNew<<endl;
strNew = NULL;
// point to other object
strNew = &str;
cout<<"strNew pointer to address: "<<strNew<<endl;
const int cvalue(10);
// iptr points to a const int object
const int *iptr = new const int(222);
cout<<"iptr value: "<<*iptr<<endl;
delete iptr;
iptr = NULL;
iptr = &cvalue;
cout<<"iptr value: "<<*iptr<<endl;
return 0;
}
一次运行的结果如下:
str object address: 0x28ff24
strNew pointer itself address: 0x28ff20
strNew pointer to address: 0x602f70
strNew pointer to address: 0x602f70
strNew pointer to address: 0x602f70
strNew pointer to address: 0x28ff24
iptr value: 222
iptr value: 10
程序中间将原来指向 new 创建的对象的指针重定向到一般的变量,可以看到指针存放地址的改变。另外需要注意,在释放 new 对象之前不要将指针重新指向某个其他对象,这样会导致原来动态创建的对象没有指针指向它,无法释放内存空间。
以上就是本文的全部内容,希望对大家的学习有所帮助。
注:相关教程知识阅读请移步到C++教程频道。










