Sunday, October 30, 2011

A comparison of boost::bind and std::bind

It is time for us to follow up new C++ standard. Just see the difference between boost::bind and std::bind below. For C++ lambda, check out C++11 or a quick guide to Lambdas in C++. Do not use std::ref if the functor will be called asynchronously.

#include <boost/bind.hpp>
 
//g++ test.cc -std=c++0x
 
struct A
{
  A() { std::cout << "A" << std::endl; }
  A(const A& a) { std::cout << "A(A)" << std::endl; }
  A& operator=(const A& a) { std::cout << "A=" << std::endl; return *this; }
  ~A() { std::cout << "~A" << std::endl; }
};
 
int main() {
  auto f = [=](A& a) {}; 
  A a;
  std::cout << std::endl;
  std::cout << "boost" << std::endl;
  boost::bind<void>(f, a)();
  std::cout << std::endl;
  std::cout << "boost ref" << std::endl;
  boost::bind<void>(f, std::ref(a))();
  std::cout << std::endl;
  std::cout << "std ref" << std::endl;
  std::bind(f, std::ref(a))();
  std::cout << std::endl;
  std::cout << "std" << std::endl;
  std::bind(f, a)();
  std::cout << std::endl;
  std::cout << "end of main" << std::endl;
  return 0;
}

Output:

A

boost
A(A)
A(A)
A(A)
A(A)
~A
A(A)
~A
~A
~A
~A

boost ref

std ref

std
A(A)
~A

end of main
~A

No comments:

Post a Comment