(目录)


一、function模版

可以实现函数的回调。c++11支持。

#include <iostream>
#include <functional> // std::function

using namespace std;

void func() {
	cout << "Line: " << __LINE__ << " " << __FUNCTION__ << endl;
}

class Test {
public:
	static int test_func(int a) {
		cout << "Line: " << __LINE__ << " " << __FUNCTION__ << "(int a)"
				<< endl;
		return a;
	}
};

class MyFunc {
public:
	int operator()(int a) {
		cout << "Line: " << __LINE__ << " " << __FUNCTION__ << "(int a)"
				<< endl;
		return a;
	}
};
int main(int argc, const char **argv) {
	function<void(void)> f1 = func;
	f1();

	function<int(int)> f2 = Test::test_func;
	cout << f2(3) << endl;

	MyFunc fo;
	function<int(int)> f3 = fo;
	cout << f3(10) << endl;

	return 0;
}

二、bind绑定函数

可以实现函数的回调。c++11支持。

#include <iostream>
#include <functional> // std::function

using namespace std;
using namespace std::placeholders;

class Test {
public:
	void func(int x, int y) {
		cout << "Line: " << __LINE__ << " " << __FUNCTION__ << endl;
		cout << "x=" << x << " y=" << y << endl;
	}

	int a;
};

int main(int argc, const char **argv) {
	Test obj;

	// 绑定成员函数
	function<void(int, int)> f1 = bind(&Test::func, &obj, _1, _2); // _1对应第一个实参, _2对应第二个实参
	f1(10, 20);

	// 绑定成员变量
	function<int& ()> f2 = bind(&Test::a, &obj);
	f2() = 30; // 等价于obj.a=30
	cout << obj.a << endl;

	return 0;
}

三、左值和右值

  • 左值:可以在等号左边,也可以在等号右边。有名字,可以取地址。 比如:变量名,返回左值引用的函数调用(一个&),++i,--i,(i=9)=100;,(i+=10)=10;,解引用*p。 主要用于避免对象拷贝。
  • 右值:只能在等号右边。没有名字,不可以取地址。 比如: 纯右值——字面值,返回非引用类型的函数调用,临时变量,i++,i--,算数表达式,逻辑表达式,比较表达式。 将亡值——c++11新引入的右值引用(移动语义)相关的类型。临时对象,return 局部本地对象,可以触发移动构造或移动赋值。 主要用于实现移动语义,实现完美转发。
T(const T &) { // 左值版本的构造
    cout << "T(const T &) 拷贝构造" << endl;
}

T& operator=(const T &) { // 左值版本的赋值
    cout << "T& operator=(const T &) 拷贝赋值" << endl;
}

T(T &&) { // 右值版本的构造
    cout << "T(T &&) 移动构造" << endl;
}

T& operator=(T &&) { // 右值版本的赋值
    cout << "T& operator=(T &&) 移动赋值" << endl;
}