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?
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
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 = newint ;
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.
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
}