【发布时间】:2011-12-28 18:51:55
【问题描述】:
这是我的代码:
#include <vector>
#include <stdio.h>
#include <iostream>
using namespace std;
class Foo
{
public:
Foo()
{
}
~Foo()
{
}
void Bar()
{
cout << "bar" << endl;
}
};
template <class T>
void deleteVectorOfPointers( T * inVectorOfPointers )
{
typename T::iterator i;
for ( i = inVectorOfPointers->begin() ; i < inVectorOfPointers->end(); i++ )
{
delete * i;
}
delete inVectorOfPointers;
}
int main()
{
//create pointer to a vector of pointers to foo
vector<Foo*>* pMyVec = new vector<Foo*>();
//create a pointer to foo
Foo* pMyFoo = new Foo();
//add new foo pointer to pMyVec
pMyVec->push_back(pMyFoo);
//call Bar on 0th Foo element of pMyVec
pMyVec->at(0)->Bar();
//attempt to delete the pointers inside the vector and the vector itself
deleteVectorOfPointers(pMyVec);
//call Bar on 0th Foo element of pMyVec
pMyVec->at(0)->Bar();
//call Bar directly from the pointer created in this scope
pMyFoo->Bar();
return 0;
}
我正在尝试删除指向向量的指针以及向量内的所有指针。但是,在我尝试这样做之后,Bar 仍然执行得很好......
【问题讨论】:
-
删除后访问对象成员是未定义的行为,这不是测试代码是否有效的方法。
-
所以...对象成员在删除指向该对象的指针后仍然可以访问?
-
它是未定义的,这意味着如果没有任何东西覆盖曾经存在的内存,则数据可能是可访问的。如前所述,不要依赖未定义的行为来测试您的代码。
-
嗯,不是吗?这就是为什么指针在删除后通常设置为 NULL(即阻止代码使用!)