[英]Why does a function expecting a reference work with a pointer?
I'm writing a program in C++ that uses a C library.我正在使用 C 库在 C++ 中编写一个程序。 This library takes pointers to functions for callbacks, and I want it to call instance methods.
这个库接受回调函数的指针,我希望它调用实例方法。 Fortunately, the library takes an extra data parameter that's just a "void *" and is passed unchanged to the callback.
幸运的是,该库采用了一个额外的数据参数,它只是一个“void *”,并且原封不动地传递给回调。 So, I created a generic callback wrapper function.
所以,我创建了一个通用的回调包装器 function。
void callbackWrapper(std::function<void ()> &func) {
func();
}
Now, when I need to register a callback in the library, I pass a pointer to the callbackWrapper function as the function to call, and a pointer to a std::function as the extra data parameter.现在,当我需要在库中注册回调时,我将指向 callbackWrapper function 的指针作为要调用的 function 传递,并将指向 std::ZC1C425268E68385D1AB5074F14 的指针作为额外数据参数传递。 When the callback happens, it calls my wrapper, which then calls the actual method/lambda/whatever I really wanted to call.
当回调发生时,它会调用我的包装器,然后它会调用实际的方法/lambda/我真正想调用的任何东西。
But, there's a bug in the above code.但是,上面的代码中有一个错误。 I used "&" rather than "*", which means the function is expecting a reference to a std::function, not a pointer.
我使用“&”而不是“*”,这意味着 function 期望引用std::function,而不是指针。 The function should have been defined like so:
function应该这样定义:
void callbackWrapper(std::function<void ()> *func) {
(*func)();
}
I didn't notice the bug for quite a while -- because it worked perfectly.很长一段时间我都没有注意到这个错误——因为它工作得很好。 I only noticed because I was tracking down an unrelated bug, and just happened to see it.
我只是注意到,因为我正在追踪一个不相关的错误,并且碰巧看到了它。 So, my question is, why?
所以,我的问题是,为什么? I have three possible answers:
我有三个可能的答案:
Are any of my theories correct?我的任何理论都是正确的吗? If not, what happened?
如果没有,发生了什么?
It is most likely that case 3 is true for your example.对于您的示例,情况 3 很可能是正确的。
It is very sensible to pass references as if they were pointers, most ABIs likely do this.将引用作为指针传递是非常明智的,大多数 ABI 都可能这样做。
For example, the Itanium C++ ABI says (this is the ABI which is used for example on Linux/x64):例如,Itanium C++ ABI 说(这是在 Linux/x64 上使用的 ABI):
Reference parameters are handled by passing a pointer to the object bound to the reference.
引用参数通过传递指向绑定到引用的 object 的指针来处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.