C++函数参数探究
上来先给结论:
1、函数参数带【&】表示引用,参数传入不会调用复制构造函数,否则会通过复制构造函数构建临时值
2、如果没有重载【&&】右值引用函数,【const &】也可以接收右值,都分配在栈空间
首先定义类A,编写构造函数、析构函数和赋值运算符
class A { public: int val; A(int v = 0) : val(v) { cout << val << ": A construct" << endl; } ~A() { cout << val << ": A destructor" << endl; } A(const A &other) : val(other.val) { cout << val << ": A copy construct" << endl; } A(A &&other) : val(other.val) { cout << val << ": A move construct" << endl; } A &operator=(const A &other) { val = other.val; cout << val << ": A operator= invoke" << endl; return *this; } };
其他函数调用代码ru'xi
void funObj(A a) { cout << "in funObj" << endl; } void func(A &a) { cout << "in func0" << endl; } void func(const A &a) { cout << "in func1" << endl; } void func(A &&a) { cout << "in func2" << endl; } int main() { A obj(-1); funObj(obj); cout << "out obj" << endl; A ref; func(ref); cout << "out ref" << endl; const A constRef(1); func(constRef); cout << "out constRef" << endl; func(A(2)); cout << "out rightRef" << endl; return 0; }
输出如下:
-1: A construct // obj在main中构造,main结束后销毁 -1: A copy construct // obj传入参数, 调用复制构造函数生成临时对象a in funObj // 进入普通参数函数 -1: A destructor // 普通参数函数结束, 临时对象a被销毁 out obj // 普通参数函数退出 0: A construct // ref在main中构造, main结束后销毁 in func0 // 进入引用参数函数 out ref // 引用参数函数退出 1: A construct // 常量 constRef在main中构造, main结束后销毁 in func1 // 进入常量引用参数函数 out constRef // 常量引用参数函数退出 2: A construct // 右值构造 in func2 // 被右值引用参数接收, 分配到栈内存 2: A destructor // 右值引用参数函数结束, 回收栈内存 out rightRef // 右值引用参数函数退出 1: A destructor // main函数结束, 销毁 1 0: A destructor // main函数结束, 销毁 0 -1: A destructor // main函数结束, 销毁 -1