完美转发及其实现
- 函数模版可以将自己的参数完美地转发给内部调用的其他函数。所谓完美,即不仅能准确地转发参数的值,还能保证被转发参数的左右值属性不变
- 引用折叠:如果任一引用为左值引用,则结果为左值引用,否则为右值引用。
& && -> &
&& & -> &
& & -> &
&& && -> &&
void actualRun(int a) {
}
template <typename T>
void testPerfectForward(T &¶m) {
actualRun(param);
}
void testPerfectForwardMain() {
int a = 0;
testPerfectForward(a);
}
上述 T 为int &。 那么整个为 int & &&-> int &
回到完美转发,假设现在我需要转发a,那么注意一下实现完美转发需要这样写
template <typename T>
void testPerfectForward1(T &¶m) {
actualRun(std::forward(param));
}
forward大致实现原理
static_cast + &&
template <typename T>
T&& forwad(T ¶m) {
return static_cast<T&&>(param);
}
注意其实std::move底层实现也是 static_cast
C++11 nullptr:初始化空指针
- #define NULL 0
#include <iostream>
using namespace std;
void isnull(void *c){
cout << "void*c" << endl;
}
void isnull(int n){
cout << "int n" << endl;
}
void testNull1