Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete vector of pointers

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...

like image 327
LunchMarble Avatar asked Aug 01 '26 15:08

LunchMarble


2 Answers

It causes undefined-behavior. It means that anything can happen. This:

*reinterpret_cast<int*>(0x12345678) = 314159;

may also work... So what?

like image 199
Yakov Galka Avatar answered Aug 04 '26 06:08

Yakov Galka


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.

like image 44
Hicham Avatar answered Aug 04 '26 06:08

Hicham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!