Why don't raw pointer in vector become nullptr?

161 views Asked by At

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)
}
1

There are 1 answers

12
sparrow On

Thank you for all!!

Just now, I understand intPtr and ptrVec[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.


std::vector<int*> ptrVec;
{
    int* intPtr = new int(1);
    ptrVec.push_back(intPtr);
}

for(auto itr = ptrVec.begin(); itr!=ptrVec.end(); ++itr)
{
    delete *itr; 
}
ptrVec.clear();

  1. New raw pointer when push_back directly. You only have to delete elements of vector.

std::vector<int*> ptrVec;
ptrVec.push_back(new int(1));

for(auto itr = ptrVec.begin(); itr!=ptrVec.end(); ++itr)
{
    delete *itr; 
}
ptrVec.clear();

  1. Use shared_ptr

std::vector<std::shared_ptr<int>> ptrVec;
ptrVec.push_back(std::make_shared<int>(1));

ptrVec.clear();