Min*_*wth 3 c++ pointers vector
这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我试图删除一个指向矢量的指针以及矢量内的所有指针.但是,在我尝试这样做之后,Bar仍然执行得很好......
它会导致未定义的行为.这意味着任何事情都可能发生.这个:
*reinterpret_cast<int*>(0x12345678) = 314159;
Run Code Online (Sandbox Code Playgroud)
也可以工作......那又怎样?