I want to dynamically-allocate an int
and then push the corresponding pointer into the vector. After use, I set to nullptr
all the elements of vector, but original pointer doesn't become nullptr
.
Why does this happen?
#include <vector>
int main(void)
{
int* intPtr = new int(1);
printf("%p¥n",intPtr); //(a)
std::vector<int*> ptrVec;
ptrVec.push_back(intPtr);
for(auto* ptr : ptrVec)
{
delete ptr;
ptr = nullptr;
printf("%p¥n",ptr); // (b) =>(nil) as expected.
}
printf("%p¥n",intPtr); //(c) is same with (a), opposite to my expect:(nil)
}
Thank you for all!!
Just now, I understand
intPtr
andptrVec[0]
points to same place, but they are different variables because intPtr is copied when push_back.To prevent memory leak in this case, there are three ways.
1.Delete both elements of vector and original pointer . But it is not safe for human mistake.