【发布时间】:2012-10-23 05:13:17
【问题描述】:
假设:
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
}
既然指针被删除了,重用它不是有问题吗?
【问题讨论】:
-
不要将指针与其“指向”的对象混淆。
-
是的,您可以将指针重新分配给新的/不同的对象
-
指针就像任何其他变量一样,如果您不再将它用于其他任何事情,您可以将它重用于任何用途。你不会问它是否是一个普通的
int变量,对吧? ;) -
@ViniyoShouta 不,你不应该(回应你对 pst 评论的回复)。
-
相关问题(同样的问题,但针对 C)stackoverflow.com/questions/504948/…
标签: c++ pointers delete-operator