【发布时间】:2014-06-30 21:10:37
【问题描述】:
我目前正在为我的 C++11/OpenGL3.3 项目开发 GUI,并且我正在考虑为交互式 GUI 元素制作某种回调系统。我使用了 JS/jQuery,我真的很喜欢为我想要的每个网站元素定义就地方法的系统,例如 onMouseOver、onClick。我发现委托是我获得此类功能的最佳方式。
示例代码:
class Button {
public:
// ...
// method (not needed in real-life, just to "show" it)
void MouseOver(int x, int y) { onMouseOver(this, x, y); }
// variable
std::function<void(Button*, int, int)> onMouseOver;
}
void someFunction(...) {
// ...
Button t = new Button(...);
t.onMouseOver = [](Button* this, int x, int y) -> void { some_code_here };
// ...
}
主要问题:
但我担心我刚刚创建的特定 onMouseOver 函数的范围 - 该指针在程序结束之前是否有效?有人能解释一下该函数在剩余的应用程序生命周期中究竟会发生什么吗?
其他问题:
有没有更好的方法来做这样的事情?更简单/更高效?我见过很多“不可能的快”——真的有那么慢吗?
【问题讨论】:
标签: c++11 lambda delegates scope