5

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?

1
  • 1
    auto bla = mutable [s]() { ... } like this maybe? Commented Jul 28, 2020 at 11:33

2 Answers 2

12

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();
};
Sign up to request clarification or add additional context in comments.

Comments

-1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.