tom
tom

Reputation: 507

Is this lambda capture issue a gcc compiler bug?

Minimum working example:

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

Compiler error:

$ 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 believe i should be captured as a value, but it seems to be captured as a const value.

Compiler version:

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

Upvotes: 3

Views: 505

Answers (1)

Columbo
Columbo

Reputation: 60979

The shared_ptr is a member of the closure object. And the operator() is marked const.
You can therefore not modify i, i.e. call non-const member functions like reset.

Try

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

Upvotes: 7

Related Questions