Here's my code:
#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;
}
I am trying to delete a pointer to a vector as well as all the pointers inside of the vector. However, Bar is still executing just fine after I try to do this...
It causes undefined-behavior. It means that anything can happen. This:
*reinterpret_cast<int*>(0x12345678) = 314159;
may also work... So what?
what you pointed is an undifined behaviour. the vector and object foo() are really deleted...
you just have the adress of the deleted vector written on pMyVec so it can access the data you put on it before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With