是否可以检测lambda在捕获组中是否具有"this"? [英] Is it possible to detect if a lambda has “this” in the capture group?

查看:51
本文介绍了是否可以检测lambda在捕获组中是否具有"this"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c ++ 17中,可以进行模板元编程来检测"this"是否是捕获组的一部分吗?还是在运行时?

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?

我有一个A类,它接受lambda供以后调用.但是,如果拥有A的对象B在它给A的lambda中捕获了"this",则可能导致微妙的使用后释放.在这种情况下能够崩溃将很有价值.

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.

我知道他们不会是100%(例如,用户可以将其捕获为"a = this"或"b =(void *)this").我也不希望能够捕获所有问题(例如,如果捕获对成员变量的引用).我只是想对明显错误的情况增加一些信心

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

推荐答案

lambda只比编译器生成的具有 operator()重载的类.模板编程中没有机制可以(跨平台)检测编译器是否生成了特定类型,更不用说内省成员"列表了.该课程的学生来弄清楚它捕获了什么以及如何捕获.

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.

这篇关于是否可以检测lambda在捕获组中是否具有"this"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆