boost::bind 与具有引用参数的函数
我注意到,当将引用参数传递给 boost bind 时,这些参数不会像引用一样起作用。 相反,boost 创建该成员的另一个副本,并且原始传入的变量保持不变。
当我更改对指针的引用时,一切正常。
我的问题是:
是否可以使引用起作用,或者至少在尝试使用引用参数时给出编译错误?
I noticed that when passing reference parameters to boost bind, those parameters won't act like references. Instead boost creates another copy of the member and the original passed in variable remains unchanged.
When I change the references to pointers, everything works ok.
My question is:
Is it possible to get references to work, or at least give a compiling error when it tries to use reference parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bind 的 boost 文档 建议您可以为此使用 boost::ref 和 boost::cref 。
The boost documentation for bind suggests that you can use boost::ref and boost::cref for this.
我遇到了类似的问题,每当声明绑定中使用的方法采用引用参数时,都希望通过引用传递绑定参数。 然而,这种情况并非如此! 无论方法是如何声明的,您都需要将绑定参数(即通过引用传递)显式包装在 boost::ref() 或 boost::cref() 中。
示例:
现在,以下绑定:
实际上将复制 ClassA 对象(我理解这是一个临时分配,被调用的方法不应该保留对它的引用,因为这不是引用实际对象,但对象的副本)。
但是,以下绑定:
将不会创建副本,而是使用引用来创建绑定对象。
I ran into similar issue expecting a bind parameter to be passed by reference whenever the method used in the bind was declared to take a reference parameter. However this is NOT the case! You will need to explicitly wrap the bind parameter (that is to be passed by reference) in a boost::ref() or boost::cref() regardless of how the method is declared.
Example:
now, the following binding:
will actually make a COPY of the ClassA object (which i understand it is a temporary allocation and the called method should not keep a reference to it since this is not the reference of the actual object but to a copy of the object).
however, the following binding:
will not make a copy, but use a reference to create the bind object.