可以boost :: bind与引用一起使用而不复制吗?

ste*_*anv 1 c++ boost

以下代码显示使用boost :: bind时复制通过引用传递的参数.有没有办法防止复制而不诉诸指针(我目前用作解决方法)?(用gcc 4.4.3测试)

#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>

void function1(int& x)
{
  std::cout << "function1 &x: " << &x << std::endl;
}

int main()
{
  int y = 0;
  std::cout << "main &y: " << &y << std::endl;

  boost::function<void()> f = boost::bind(function1, y);
  f();
}
Run Code Online (Sandbox Code Playgroud)

Ton*_*ion 7

你应该使用boost :: ref来传递对boost绑定的引用.

boost::function<void()> f = boost::bind(function1, boost::ref(y));
Run Code Online (Sandbox Code Playgroud)