问题
Given the following test code
#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;
}
I get the following output:
$ g++ tr1BindDtorTest.cpp && ./a.out
enter:
cl()
ref:
cl()[copy]
cl()[copy]
cl()[copy]
~cl()
~cl()
~cl()
ptr:
exit:
~cl()
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]
回答1:
Instead of this:
tr1::bind(&f1, data);
You need this:
tr1::bind(&f1, tr1::ref(data));
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().
回答2:
See cppreference documentation:
The arguments to bind are copied or moved, and are never passed by reference unless wrapped in std::ref or std::cref.
来源:https://stackoverflow.com/questions/21494914/tr1bind-pass-by-reference-is-this-behavior-really-expected