引用初始化的重要细节
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了引用初始化的重要细节相关的知识,希望对你有一定的参考价值。
#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 = (0x7fffc5b81cd0, 0)
TestType(int &rv), this = 0x7fffc5b81ce0, m_data = (0x7fffc5b81ce0, 100), rv = (0x7fffc5b81cfc, 100).
i = (0x7fffc5b81cfc, 200)
TestType(int &rv), this = 0x7fffc5b81cf0, m_data = (0x7fffc5b81cf0, 200), rv = (0x7fffc5b81cfc, 200).
本文出自 “用C++写诗” 博客,谢绝转载!
以上是关于引用初始化的重要细节的主要内容,如果未能解决你的问题,请参考以下文章