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

时间:2014-12-14 18:30:55

标签: 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应该被捕获为一个值,但它似乎被捕获为一个const值。

编译器版本:

g++ (GCC) 4.9.2 20141101 (Red Hat 4.9.2-1)

1 个答案:

答案 0 :(得分:7)

shared_ptr是闭包对象的成员。 operator()已标记为const。因此,您无法修改i,即调用非const成员函数,例如reset

尝试

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