vector<myclass*> and scope

Hello,

what happens with a pointer stored in a std::vector (e.g. myclass* in std::vector<myclass*>) when the pointer gets destroyed (e.g. local pointer and leaving local scope)? Does the pointer in the vector get destroyed as well? Does it get invalid?

Thanks!
the pointer in the vector will be destroyed, but the object pointed to (myclass) will not be destroyed
Assuming I dynamically allocated the object? Because that's not the case in my szenario!
hm? Either you do dynamically allocate the object or not.

It doesn't matter whether the object pointed to exists or how it comes to existence, the vector cares only for its data type (the pointer in this case) not the object pointed to!
This might even lead to a memory leak
Ah I see. But in this example both, pointer and object should get destroyed right?

1
2
3
4
5
6
7
8
9
10
11
void myFunc() {
    MyClass object = MyClass();
    MyClass* pointer = &object;
    std::vector<MyClass*> vector = std::vector<MyClass*>();
    vector.push_back(pointer);
}

void test() {
    myFunc();
    // Object and pointer are destroyed (the pointer in vector as well!)
}


Last edited on
If you're talking about something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>

void addTwo(std::vector<int*>& v)
{
    int a ;
    v.push_back(&a) ;
    int* b = new int ;
    v.push_back(b) ;
    delete b ;
}

int main()
{
    std::vector<int*> vec ;
    addTwo(vec) ;

    // vec retains the pointers with invalid addresses; 
    // dereferencing vec[0] or vec[1] will result in undefined behavior.
}


Then, no, the pointers are not destroyed, and no, you cannot safely use either.
Last edited on
Yes that is what I ment cire! So I'm responsible for removing the pointer from the vector when the pointer gets destroyed/invalid?
So I'm responsible for removing the pointer from the vector when the pointer gets destroyed/invalid?

Yes.
In this case, Yes. Becouse "*pointer" points to "&object". "Object" will be destroyed at the end of myfunc so memory allocated for "object" is freed.

But if you used instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void myFunc() {
    MyClass* pointer = new MyClass();
    std::vector<MyClass*> vector = std::vector<MyClass*>();
    vector.push_back(pointer);
}

void test() {
    myFunc();
    //"pointer" is not valid here. 
    //Vector internally deleted its own pointer (that is actually MyClass **, becouse vector
    //                    stores a dinamically allocated pointer for the specifyed data type)
    // but memory allocated with "new MyClass" for pointer is not freed. 
    //             and you could not delete it becouse you have no variable that remember
    //             the address of "* pointer" to delete
}
Last edited on
Topic archived. No new replies allowed.