gpt4 book ai didi

c++ - 尝试在 vector 中查找 unique_ptr 时出现编译错误

转载 作者:太空狗 更新时间:2023-10-29 20:35:56 24 4
gpt4 key购买 nike

这段代码:

#include <memory>
#include <vector>
#include <algorithm>

struct Foo
{
int bar;

Foo(const int val) :
bar(val)
{
}
};

int main() {
std::vector<std::unique_ptr<Foo>> vec;
vec.emplace_back(std::make_unique<Foo>(42));
Foo* ptr = vec.back().get();
auto& it = std::find_if(vec.begin(), vec.end(), [&](std::unique_ptr<Foo>& p)
{
return p.get() == ptr;
});
if (it != vec.end())
{
vec.erase(it);
}

return 0;
}

在 MSVC 中工作正常,但在 GCC 5.1 中出错:

prog.cpp: In function 'int main()':

prog.cpp:19:25: error: invalid initialization of non-const reference of type '__gnu_cxx::__normal_iterator*, std::vector > >&' from an rvalue of type '__gnu_cxx::__normal_iterator*, std::vector > >' auto& it = std::find_if(vec.begin(), vec.end(), [&](std::unique_ptr& p)

  1. 哪个编译器有问题?
  2. 如何从 std::unique_ptrstd::vector 中正确删除指针?

最佳答案

gcc 在这里是正确的。您不能用右值初始化左值引用,而您这样做是为了 it 对迭代器的引用(std::find_if 返回右值)

auto& it = std::find_if(vec.begin(), vec.end(), [&](std::unique_ptr<Foo>& p)
^

要么把它变成一个对象:

auto it = std::find_if(vec.begin(), vec.end(), [&](std::unique_ptr<Foo>& p)

demo

或常量引用:

auto const& it = std::find_if(vec.begin(), vec.end(), [&](std::unique_ptr<Foo>& p)

demo

除此之外,您从 vector 中删除元素的代码是正确的

关于c++ - 尝试在 vector 中查找 unique_ptr 时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40455882/

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