boost::bind 与具有引用参数的函数

发布于 2024-07-11 23:52:52 字数 174 浏览 4 评论 0原文

我注意到,当将引用参数传递给 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

镜花水月 2024-07-18 23:52:52

bind 的 boost 文档 建议您可以为此使用 boost::ref 和 boost::cref 。

The boost documentation for bind suggests that you can use boost::ref and boost::cref for this.

城歌 2024-07-18 23:52:52

我遇到了类似的问题,每当声明绑定中使用的方法采用引用参数时,都希望通过引用传递绑定参数。 然而,这种情况并非如此! 无论方法是如何声明的,您都需要将绑定参数(即通过引用传递)显式包装在 boost::ref() 或 boost::cref() 中。

示例:

ClassA myClassAParameter
void Method(ClassA ¶m);

现在,以下绑定:

callback = boost::bind(&Method, myClassAParameter);

实际上将复制 ClassA 对象(我理解这是一个临时分配,被调用的方法不应该保留对它的引用,因为这不是引用实际对象,但对象的副本)。

但是,以下绑定:

callback = boost::bind(&Method, boost::ref(myClassAParameter));

不会创建副本,而是使用引用来创建绑定对象。

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:

ClassA myClassAParameter
void Method(ClassA ¶m);

now, the following binding:

callback = boost::bind(&Method, myClassAParameter);

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:

callback = boost::bind(&Method, boost::ref(myClassAParameter));

will not make a copy, but use a reference to create the bind object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文