shoosh
shoosh

Reputation: 78914

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?

Upvotes: 5

Views: 2111

Answers (2)

blueberryman
blueberryman

Reputation: 19

In C++17, you can do this:

vector<int>a;
auto lambda = [a=std::as_const(a)](){};

It comes from this: Lambda: Why are captured-by-value values const, but capture-by-reference values not?

Upvotes: 0

Yksisarvinen
Yksisarvinen

Reputation: 22201

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

Upvotes: 11

Related Questions