只是询问哪个是更新版本的c ++中更好的选择来处理成员函数的回调。 任何帮助将不胜感激,希望这个例子也会有所帮助。
template<class T> void addCallBack(void(T::*someFunc)(int), T* instance) { func = std::bind(someFunc, instance, _1); } std::function<void(int)> func ;要么
template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } } std::function<void(int)> func;Just inquiring which is a better choice in newer versions of c++ to handle callbacks of member functions. Any help would be much appreciated, hopefully the example will help also.
template<class T> void addCallBack(void(T::*someFunc)(int), T* instance) { func = std::bind(someFunc, instance, _1); } std::function<void(int)> func ;or
template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } } std::function<void(int)> func;最满意答案
这个:
template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } }正在通过引用捕获参数instance ,这超出了addCallBack()末尾的范围,因此您最终会得到一个悬空引用。 所以,绝对不是那样的。
你想要做的是:
func = [instance](int x){ instance->someFunc(x); }要不就:
func = [=](int x){ instance->someFunc(x); }现在,在那之间不会出现功能差异† :
func = std::bind(&T::someFunc, instance, std::placeholders::_1);但是lambda通常更容易阅读(就像在这种情况下一样),并且更容易内联,并且更能够执行任意复杂的事情。 后两者在这种情况下并不重要 - 但基本上总是喜欢lambdas是很好的理由。
†当然,如果someFunc是一个重载名称,这someFunc ,这是另一个更喜欢lambda的理由 - 这将始终有效。
This:
template<class T> void addCallBack(T* instance) { func = [&instance](int x) { instance->someFunc(x); } }is capturing the argument instance by reference, which goes out of scope at the end of addCallBack() so you end up with a dangling reference. So, definitely not that.
What you want to do is:
func = [instance](int x){ instance->someFunc(x); }or just:
func = [=](int x){ instance->someFunc(x); }Now there isn't going to be a functional difference† between that and:
func = std::bind(&T::someFunc, instance, std::placeholders::_1);but the lambda is going to be typically easier to read (as it is in this case), and easier to inline, and is more capable of doing arbitrary complex things. The latter two don't matter in this case - but are good reasons to basically always prefer lambdas.
†Of course, this doesn't work if someFunc is an overloaded name, which is one more reason to prefer a lambda - which will always work.
更多推荐
发布评论