/* 非常量引用无效 */
#include <iostream>
using namespace std;
/*
C++标准的规定:非常量的引用不能指向临时对象:
为了防止给常量或临时变量(只有瞬间的生命周期)赋值(易产生bug),只许使用const引用之。
*/
class Student
{
public:
Student(int num) :_num(num)
{
}
private:
int _num;
};
void send(const Student & s)
{
}
int test()
{
send(Student(10)); //error:用类型为‘Student’的右值初始化类型为‘Student&’的非常量引用无效
/*
分析:
这里Student(10)的作用于仅限于send(),过了send()函数就会被释放,所以说Student(10)是一个临时对象
C++标准的规定:非常量的引用不能指向临时对象,为了防止给常量或临时变量(只有瞬间的生命周期)赋值(易产生bug)
,只许使用const引用之。
所以应该修改send(const Student & s);
注意不加const,可能在vs中可以编译通过,但是在g++可能编译错误
*/
return 0;
}
int main()
{
test();
getchar();
printf("ok\n");
return 0;
}