c++lambdashared-ptrcapture

value turned const in lambda capture?


I have this simple code:

std::shared_ptr<std::string> s;

auto bla = [s]() {
    s.reset();
};

What I meant this to do is that the shared_ptr be captured by the lambda and then reset once the lambda is called.
Compiling this with VS yields the following error:

error C2662: 'void std::shared_ptr<std::string>::reset(void) noexcept': cannot convert 'this' pointer from 'const std::shared_ptr<std::string>' to 'std::shared_ptr<std::string> &' 1>...: message : Conversion loses qualifiers

What gives? How come the shared_ptr turns to const shared_ptr?


Solution

  • When capturing by copy, all captured objects are implicitly const. You have to explicitly mark lambda as mutable to disable that:

    auto bla = [s]() mutable {
        s.reset();
    };
    

    Also, if you want to reset actual s and not a copy, you want to capture by reference. You don't need mutable when capturing by reference, in this case constness is inferred from the actual object:

    auto bla = [&s]() {
        s.reset();
    };