首页 > 代码库 > 引用初始化的重要细节
引用初始化的重要细节
#include<iostream> using std::cout; using std::endl; template<typename T> void swap(T&a, T&b){ a = a ^ b; b = a ^ b; a = a ^ b; } int main(){ short s = 50; //error: invalid initialization of reference of type ‘int&’ from expression of type ‘short int’ //无效的初始化:用‘short int‘类型的表达式来初始化‘int&‘类型的引用。 //原因:用左值来初始化引用时,类型必须一致,不允许隐式转换。 //int &ri1 = s; //invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ //无效的初始化:用‘int‘类型的右值来初始化‘int &‘类型的non-const引用。 //原因:用右值来初始化引用时,会产生一个同类型的匿名临时变量,对表达式的值进行隐式转换,再对这个临时变量赋值。 //int &ri2 = 50; //如果允许对这个临时变量定义一个non-const类型的引用,那么后续代码对这个引用的写操作毫无意义。例如: //int &i = 3; //int& j = 4; //swap<int>(i,j); //将无法对i,j进行交换。 //有效的初始化:用‘int‘类型的右值来初始化‘int &‘类型的const引用。 const int &ri3 = 60; }
下面的代码显示,用右值初始化一个引用时,生成了一个匿名临时变量:
#include<iostream> using std::cout; using std::endl; class TestType{ int m_data; public: TestType() : m_data(0) { cout << __FUNCTION__ << "(), this = " << this; cout << ", m_data = (" << &m_data << ", " << m_data << ")\n"; } //TestType(int val) : m_data(val) { // cout << __FUNCTION__ << "(int val), this = " << this; // cout << ", m_data = (" << &m_data << ", " << m_data << ")"; // cout << ", val = (" << &val << ", " << val << ").\n"; //} TestType(const int &rv) : m_data(rv) { cout << __FUNCTION__ << "(int &rv), this = " << this; cout << ", m_data = (" << &m_data << ", " << m_data << ")"; cout << ", rv = (" << &rv << ", " << rv << ").\n"; } }; int main(){ cout << "sizeof(TestType) = " << sizeof(TestType) << endl; TestType dat1; TestType dat2(100); int i = 200; cout << "i = (" << &i << ", " << i << ")\n"; TestType dat3(i); return 0; }
运行结果:
sizeof(TestType) = 4
TestType(), this = 0x7fffc5b81cd0, m_data = http://www.mamicode.com/(0x7fffc5b81cd0, 0)
TestType(int &rv), this = 0x7fffc5b81ce0, m_data = http://www.mamicode.com/(0x7fffc5b81ce0, 100), rv = (0x7fffc5b81cfc, 100).
i = (0x7fffc5b81cfc, 200)
TestType(int &rv), this = 0x7fffc5b81cf0, m_data = http://www.mamicode.com/(0x7fffc5b81cf0, 200), rv = (0x7fffc5b81cfc, 200).
本文出自 “用C++写诗” 博客,谢绝转载!
引用初始化的重要细节
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。