TR1::绑定和通过引用传递,这种行为真的是预期的吗?

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

本文关键字:真的 绑定 引用 TR1      更新时间:2023-10-16

给定以下测试代码

#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()

当我创建涉及对我的类/结构对象的引用的绑定时,会多次创建和破坏。

相同的精确测试,但使用指针没有这样的对象

我看不出为什么通过value&amp;参考,我一直认为参考是指指针的句法糖,因此,行为应该相同。

有人愿意解释吗?

[G 4.4.6 Linux&amp;4.2.1 MacOS]

而不是:

tr1::bind(&f1, data);

您需要此:

tr1::bind(&f1, tr1::ref(data));

boost具有相同的内容:如果要绑定的函数对象存储对数据的引用,则必须在boost :: bind()内使用boost :: ref()。否则,数据将始终复制到由bind()产生的绑定函数对象中。

请参阅cppReference文档:

绑定的论点是复制或移动的,从未通过 参考,除非包裹在std :: ref或std :: cref。