c – 这个lambda捕获问题是gcc编译器错误吗?

c – 这个lambda捕获问题是gcc编译器错误吗?,第1张

概述最低工作示例: #include <iostream>#include <memory>#include <string>int main(){ std::shared_ptr<std::string> i = std::make_shared<std::string>("foo"); auto f = [=]() { i.res 最低工作示例:

#include <iostream>#include <memory>#include <string>int main(){    std::shared_ptr<std::string> i = std::make_shared<std::string>("foo");    auto f = [=]()        {            i.reset();            std::cout << i.get() << "\n";        };    std::cout << i.use_count() << "\n";    f();    std::cout << i.use_count() << "\n";}

编译错误

$g++ -std=c++11 /tmp/foo.cpp /tmp/foo.cpp: In lambda function:/tmp/foo.cpp:11:12: error: passing ‘const std::shared_ptr<std::basic_string<char> >’ as ‘this’ argument of ‘voID std::__shared_ptr<_Tp,_Lp>::reset() [with _Tp = std::basic_string<char>; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’ discards qualifIErs [-fpermissive]    i.reset();

我相信我应该被捕获为一个值,但它似乎被捕获为一个const值.

编译器版本:

g++ (GCC) 4.9.2 20141101 (Red Hat 4.9.2-1)
解决方法 shared_ptr是闭包对象的成员. operator()标记为const.因此,您不能修改i,即调用非const成员函数,如reset.

尝试

auto f = [=]() mutable{    i.reset();    std::cout << i.get() << "\n";};
总结

以上是内存溢出为你收集整理的c – 这个lambda捕获问题是gcc编译器错误吗?全部内容,希望文章能够帮你解决c – 这个lambda捕获问题是gcc编译器错误吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1216436.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存