tr1 :: bind&通过引用,这是真的期望的行为吗? [英] tr1::bind & pass by reference, is this behavior really expected?
问题描述
给定以下测试代码
#include <iostream>
#include <tr1/functional>
using namespace std;
struct cl {
cl(){ cout << " cl()\n"; }
cl(const cl& from){ cout << " cl()[copy]\n"; }
~cl(){ cout << " ~cl()\n";}
};
void f1(const cl& data){}
void f2(const cl* pData){}
int main(int c, char** a)
{
cout << "enter:\n";
cl data;
cout << "ref:\n";
tr1::bind(&f1, data);
cout << "ptr:\n";
tr1::bind(&f2, &data);
cout << "exit:\n";
return 0;
}
我得到以下输出:
$ g++ tr1BindDtorTest.cpp && ./a.out
enter:
cl()
ref:
cl()[copy]
cl()[copy]
cl()[copy]
~cl()
~cl()
~cl()
ptr:
exit:
~cl()
当我创建一个绑定时,引用我的类/ struct对象被多次创建和销毁。
When I create a binding involving references to my class/struct objects are created and destroyed multiple times.
相同的精确测试,但指针没有这样的对象
Same exact test but with pointers there are no such objects
我不明白为什么行为会不同通过值&
I can't see why the behaviour will be different between pass by value & reference, I always thought of reference as syntactic sugar for pointer, and so reasoned that the behaviours should be identical.
任何人都可以解释一下?
Anyone care to explain?
[g ++ 4.4.6 linux& 4.2.1 on macos]
[g++ 4.4.6 linux & 4.2.1 on macos]
推荐答案
而不是这样:
tr1::bind(&f1, data);
您需要:
tr1::bind(&f1, tr1::ref(data));
Boost有同样的事情:boost :: ref()必须在boost :: bind )如果你想绑定的函数对象存储对数据的引用。否则,数据将总是被复制到由bind()生成的绑定函数对象中。
Boost has the same thing: boost::ref() must be used inside boost::bind() if you want the bound function object to store a reference to the data. Otherwise, the data will always be copied into the bound function object produced by bind().
这篇关于tr1 :: bind&通过引用,这是真的期望的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!