thisisdog
thisisdog

Reputation: 948

Is there a way to prevent lambda capture by reference

I'm in the middle of a refactor of existing code that relies on lambdas. In the new version of the code I'd like to defer the calls into the lambdas, so I'd like to prevent any future users from accidentally capturing by reference, as well as use the compiler to find all the offending existing code.

Is this possible with c++11?

Upvotes: 1

Views: 833

Answers (2)

xaxxon
xaxxon

Reputation: 19761

use the compiler to find all the offending existing code.

This is possible, but non-trivial using libtooling/clang plugin -- but probably not how you'd expect.

You can write a plugin that the compiler runs after it compiles all your code and that plugin can inspect the AST that clang builds while compiling your code. You can traverse the AST to find lambdas and inspect the types of their capture lists. It's pretty cool, but the documentation isn't great and it can be a time-consuming process. Probably not worth it for a one-off project.

Upvotes: 1

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275340

No. And it wouldn't help much: once lifetimes exceed the current scope, you have to both capture by value and ensure the lifetime of all pointers or referred to (in any way) resources is managed.

An async callback is a fundamentally different beast than a sync callback, and the C++ type system cannot enforce safety here.

Even if resource lifetime issues where solved, the calling code was expecting the changes caused by the lambda to occur immediately, and now they don't. Every use would have to be audited for the new pattern.

Upvotes: 1

Related Questions