tr1 :: bind&pass by reference,这种行为真的值得期待吗?

nhe*_*hed 2 c++ tr1

给出以下测试代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

$ g++ tr1BindDtorTest.cpp && ./a.out
enter:
  cl()
ref:
  cl()[copy]
  cl()[copy]
  cl()[copy]
  ~cl()
  ~cl()
  ~cl()
ptr:
exit:
  ~cl()
Run Code Online (Sandbox Code Playgroud)

当我创建一个涉及对我的类/ struct的引用的绑定时,会多次创建和销毁对象.

同样的测试,但有指针​​,没有这样的对象

我不明白为什么传递值和引用之间的行为会有所不同,我总是将引用视为指针的语法糖,因此推断行为应该是相同的.

有人在乎解释吗?

[g ++ 4.4.6 linux&4.2.1 on macos]

Joh*_*nck 6

而不是这个:

tr1::bind(&f1, data);
Run Code Online (Sandbox Code Playgroud)

你需要这个:

tr1::bind(&f1, tr1::ref(data));
Run Code Online (Sandbox Code Playgroud)

Boost具有相同的功能:如果希望绑定的函数对象存储对数据的引用,则必须在boost :: bind()中使用boost :: ref().否则,数据将始终复制到bind()生成的绑定函数对象中.