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

标签 c++ c++11 gcc lambda g++

最小工作示例:

#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();

我相信 i 应该被捕获为一个值,但它似乎被捕获为一个常量值。

编译器版本:

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 编译器错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27472571/

相关文章:

c - 为什么 gcc 中 '-l' 选项的顺序很重要?

c++ - 如何使用位掩码?

c - 为什么我不能用 -fPIE 编译但可以用 -fPIC 编译?

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?

c++ - 当在 Objective-C++ 中应用于 __weak 指针时,通过 "auto"关键字推导类型的规则是什么?

c++ - std::shared_ptr 和继承

c++ - 为什么我的 strftime() 方法没有输出我期望的年份

windows - Windows 中的 cmake 问题

c++ - 找不到基类模板的成员

c++ - 如何使用 openssl lib pem_read 从字符串中读取公钥/私钥