0

I have below code. I think all of 3 elements in the vector can be deleted and erased correctly, but the original pointer t1, t2, t3 become dangling pointers, right ? It looks like a problem if they are used in somewhere else. How to deal with them ?

typedef struct test
{
    test(int i, int j): a(i), b(j){}
    int a;
    int b;
}Test;

int main(int argc, char** argv)
{
    test* t1 = new test(1, 2);
    test* t2 = new test(1, 4);
    test* t3 = new test(1, 8);

    vector<test*> testList;
    testList.push_back(t1);
    testList.push_back(t2);
    testList.push_back(t3);

    for(auto it = testList.begin(); it!=testList.end();)
    {
        delete (*it);
        *it = nullptr;
        it = testList.erase(it);
    }

    return 0;
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Lingyi
  • 19
  • 5
  • There's nothing you can do about that. It's no different from any other situation where you delete what a pointer points to, you have to make sure you don't use any other variables that hold the same pointger. – Barmar Aug 25 '16 at 16:55
  • Consider ways to avoid expressing ownership via raw pointers. First of all, can you use containers directly instead of `new`-ing? If so, do so. But if you must `new`, then immediately put the raw pointer in a smart pointer (to manage it), such as `std::unique_ptr` and `std::shared_ptr`. Raw pointers have their uses, e.g. to just refer to objects. But those uses do not include expressing ownership. Voting to close as **too broad**. – Cheers and hth. - Alf Aug 25 '16 at 16:56
  • 3
    The solution is to use better abstractions and mechanisms. A naive solution would be `std::vector>`. A better solution would be `std::vector`. – Kerrek SB Aug 25 '16 at 16:56
  • You can use [smart pointers](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – Nikita Aug 25 '16 at 16:57
  • 2
    You fix it by making sure there are no pointers to dangle. There are at least 3 good ways to do that. Encapsulation, smart pointers, no pointers. – Kenny Ostrom Aug 25 '16 at 18:22
  • Thank you guys. I think in my project the best solution is to use smart pointer. Thanks for your help. – Lingyi Sep 01 '16 at 16:44

0 Answers0