boost::bind()是否通过引用或值复制参数

Does boost::bind() copy parameters by reference or by value?

本文关键字:引用 复制 参数 bind 是否 boost      更新时间:2023-10-16

为什么valgrind的DRD工具抱怨"线程负载冲突…大小为4":关于这样的代码:

void SomeFunction(const int& value)
{
    boost::bind(..., value); /* <-- complaines on this line
                                with last backtrace function "new(int)" */
}

boost::bind()是否通过引用或值存储值?

按值。1

但你可以通过引用复制它:

void SomeFunction(const int& value)
{
    boost::bind(..., boost::ref(value)); 
    boost::bind(..., boost::cref(value)); // by const ref
}

1http://www.boost.org/doc/libs/1_46_1/libs/bind/bind.html#Purpose

i的值的副本被存储到函数对象中。boost::ref和boost::cref可用于使函数对象存储对对象的引用,而不是副本:int i=5;

bind(f,ref(i),_1);

bind(f,cref(42),_1);