gpt4 book ai didi

c++ - 使用 std::unique 时如何防止悬挂指针?

转载 作者:搜寻专家 更新时间:2023-10-31 00:40:29 24 4
gpt4 key购买 nike

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

例如:

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;
}

最佳答案

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

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

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

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

关于c++ - 使用 std::unique 时如何防止悬挂指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14679060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com