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

Mur*_*der 2 c++ algorithm containers pointers unique

在调用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;
}
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 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());
}
Run Code Online (Sandbox Code Playgroud)

现在,你可以调用std::uniquefoos,知道什么都不会泄漏.如果您经常这样做,包装函数可能是一个好主意:

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