Is it possible to detect if a lambda has “this” in the capture group?

Viewed 122

In c++17 is it possible to do template meta-programming to detect if “this” was part of the capture group some how? Or at runtime?

I have a class A that accepts the lambda for later invocation. However, if the object B owning A captures “this” in the lambda it gives A, then it can cause a subtle use-after free. Being able to crash in this scenario would be valuable.

I’m aware their wouldn’t be 100% (eg a user could capture it as “a = this” or “b = (void*)this”). I also don’t expect to be able to capture all problems (eg if I capture a reference to a member variable). I’m just looking to add some confidence in the obviously wrong scenarios

1 Answers

A lambda is nothing more than a class generated by the compiler that has an overloaded operator(). There is no mechanism in template programming that can (cross-platform) detect if a particular type was generated by the compiler, let alone introspect into the "members" of that class to figure out what it captured and how.

You will simply have to expect users of your system to exercise proper discipline.

Related