使用std :: unique时如何防止悬空指针?

时间:2013-02-04 00:44:09

标签: c++ algorithm pointers unique containers

如何在调用std :: unique后删除向量中的指针?

例如:

struct Foo
{
    Foo(int bar) : mBar(bar) {}
    ~Foo() { std::cout << "~dtor\n"; }

    int mBar;
};

bool SortFunc(Foo * right, Foo * left) { return right->mBar < left->mBar; }

// Should I 'delete left;' in case of equality?
bool CompareFunc(Foo * right, Foo * left)
{
    return right->mBar == left->mBar;
}

// NOTE: In my code, vector is initialized in another class which I cannot modify.
void InitializeList(std::vector<Foo *> & fooList)
{
    Foo * firstFoo = new Foo(1);
    Foo * secondFoo = new Foo(2);
    // This pointer will not be in vector anymore after std::unique is called!
    Foo * thirdFoo = new Foo(1);
    Foo * forthFoo = new Foo(4);

    fooList.push_back(firstFoo);
    fooList.push_back(secondFoo);
    fooList.push_back(thirdFoo);
    fooList.push_back(forthFoo);
}

int main()
{
    { // Block exists to see if Foo::dtor is called.
    std::vector<Foo *> fooList;
    InitializeList(fooList);

    std::sort(fooList.begin(), fooList.end(), SortFunc);

    std::vector<Foo *>::iterator itrResult = fooList.end();
    // Pointer to thirdFoo is dangling after std::unique is called.
    itrResult = std::unique(fooList.begin(), fooList.end(), CompareFunc);
    fooList.erase(itrResult, fooList.end());

    // ... Other operations and clean up code.
    }
    return 0;
}

2 个答案:

答案 0 :(得分:5)

您可以通过立即将其结果包装在智能指针中,将自己与实施不当的InitializeList隔离开来:

std::vector<std::unique_ptr<Foo>> foos;
{
  std::vector<Foo *> foo_ptrs;
  InitializeList(foo_ptrs);
  foos.assign(foo_ptrs.begin(), foo_ptrs.end());
}

现在,您可以在std::unique上致电foos,并知道不会泄漏任何内容。如果您经常这样做,包装函数可能是一个好主意:

std::vector<std::unique_ptr<Foo>> get_foos() {
  std::vector<Foo *> foo_ptrs;
  InitializeList(foo_ptrs);
  return {foo_ptrs.begin(), foo_ptrs.end()};
}

答案 1 :(得分:0)

正如juanchopanza所提到的,你需要在重复的元素上明确地调用delete

漏洞在这里:

   fooList.erase(itrResult, fooList.end());

erase将简单地删除两个迭代器之间的指针。您必须首先致电delete