#include <iostream>
#include <functional>
#include <memory> // for shared_ptr
#include <thread>
class AA
{
public:
~AA() { std::cout << "desconstuct AA" << std::endl; }
int f(int a, int b) const
{
std::cout << "AA::f(int, int)\n";
return a * b;
}
};
int main()
{
using namespace std::placeholders; // for _1, _2, _3...
{
// smart pointer c++11, it will auto delete when
// pa is out of the scope, you can also specify
// deletor like this:
// std::shared_ptr<FILE, fclose> pf = fopen("a.txt", "r");
// notice we pass fclose as the second template parames, so
// when pf is out of scope, it will auto call fclose to close
// the pf, see shared_ptr for more detail.
std::shared_ptr<AA> pa(new AA);
// auto type decuction, a, b have type int
auto a = 40, b = 20;
// start thread t with a anonymous lambda function, it accept
// a, b and a functional f which accept two int type and return
// a int type, we also pass a to a, b to, and member function a->f to f,
// notice that f is use std::bind(c++11) to bind a member function, see bind
// for more detail, std::bind return a functional object, in the lambda
// functional we use nullptr(c++11) compare with f to detect whether f is null
std::thread t([](int a, int b, std::function<int (int, int)> f) {
if (nullptr != f) {
std::cout << f(a, b) << std::endl;
}
}, a, b, std::bind(&AA::f, pa, _1, _2));
t.join();
}
return 0;
}