struct Foo
{
Obj* pObj;
Foo() : pObj(NULL);
};
Obj* CreateObj()
{
//do some stuff and then
return new Obj; //obj is a class
}
int main()
{
Foo foo;
foo.pObj = CreateObj();
DoSomeOperationWithTheObj(foo.pObj);
//suppose foo is a monster that should be 'killed' or deleted now
delete foo.pObj;
foo.pObj = NULL;
//the question is can this pointer be 're-used' now like this:
foo.pObj = CreateObj(); //create another object
}
由於指針被刪除,是不是有問題,再次使用它嗎?
不要將指針與它「指向」的對象混淆。 – 2012-10-23 05:15:00
@pst你的意思是我應該做'delete * foo.pOBj'? –
是的,您可以將指針重新分配給新的/不同的對象 – mac