C++ boost::bind 函数的参数是引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/470040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
boost::bind with functions that have parameters that are references
提问by Brian R. Bondy
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.
我注意到当将引用参数传递给 boost bind 时,这些参数不会像引用一样。相反,boost 创建了该成员的另一个副本,而传入的原始变量保持不变。
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?
是否可以使引用起作用,或者至少在尝试使用引用参数时给出编译错误?
回答by Timo Geusch
The boost documentation for bindsuggests that you can use boost::ref and boost::cref for this.
回答by DolphinDream
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.
我遇到了类似的问题,希望每当绑定中使用的方法被声明为采用引用参数时,就会通过引用传递绑定参数。然而,这种情况并非如此!无论方法是如何声明的,您都需要将绑定参数(即通过引用传递)显式包装在 boost::ref() 或 boost::cref() 中。
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 notkeep a reference to it since this is not the reference of the actual object but to a copy of the object).
实际上使ClassA的对象的副本(我明白这是一个临时的分配和调用的方法应该不是一个参考保持它,因为这是不实际对象的引用,但该对象的副本)。
however, the following binding:
但是,以下绑定:
callback = boost::bind(&Method, boost::ref(myClassAParameter));
will notmake a copy, but use a referenceto create the bind object.
将不进行复印,但使用一个参考来创建绑定对象。