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]