tr1::bind & pass by reference, is this behavior really expected?

十年热恋 提交于 2019-12-11 00:30:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!