TR1::绑定和通过引用传递,这种行为真的是预期的吗?
tr1::bind & pass by reference, is this behavior really expected?
给定以下测试代码
#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。
中
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 在基于范围的for循环中使用结构化绑定声明
- 使用 LuaBridge 将 LuaJIT 绑定到C++会导致"PANIC: unprotected error"
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 在使用GPU支持编译Tensorflow时,会遇到CUDA_TOOLKIT_PATH未绑定变量
- 视觉studo 2019中的漫画和静态/动态绑定
- 将自由函数绑定为类成员函数
- 将常量指针引用绑定到非常量指针
- 在派生类中绑定非静态模板化成员函数
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 在 openGL 中多次绑定缓冲区
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 使用结构化绑定'Reflection'
- 为什么 std::绑定错误参数可以成功?
- 如何绑定 C++ gRPC 客户端的网络接口
- 在 openmp 中,omp_get_thread_num是否绑定到物理线程?
- C++绑定(已弃用)
- 运行时错误:引用绑定到类型为"int"的空指针
- TR1::绑定和通过引用传递,这种行为真的是预期的吗?
- std::bind 绑定"by value",这是真的吗?