65,210
社区成员
发帖
与我相关
我的任务
分享
如果楼主拜读过Scott Meyers的<<effective c++>>,其中谈到一个著名的设计原则叫懒人原则,意思是
不到事到临头就懒的去管。
内存的分配和释放也是一样,操作系统就利用了懒人原则,其它用户只要不指明用到某某内存,操作系统就不
会去管它,是否被释放好像与我操作系统暂时无关,你要用就用吧,反正懒的理。
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
int *p ;
public:
Test(int *ip) : p(ip) { }
void setval(int val) { *p = val;}
int getval() const{ return *p; }
};
void main()
{
int *ip = new int(20);
Test t(ip);
delete ip;
ip = NULL; //这里只是把ip指针赋0,但是t对象里的p指针还是指向的20
t.setval(10); //通过t对象的p指针还是可以修改内存(20),(因为还是有指针指向那个20内存)
cout < < t.getval() < < endl; //同样也可以读
return ;
}#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Test
{
private:
int *p ;
public:
Test(int *ip) : p(ip) { }
void setval(int val) { *p = val;}
int getval() const{ return *p; }
};
void main()
{
int *ip = new int(20);
Test t(ip);
delete ip;
ip = NULL;
t.setval(10);
ip = new int(20);//lz你加一行在这里,新分配的内存似乎与类中保存的指针已经没有关系了,但是数据却被修改了
cout << t.getval() << endl;
return ;
}