C++ 使用引用初始化类成员
我总是觉得我不应该使用引用来初始化类成员,因为C++ 使用引用初始化类成员,c++,class,reference,constants,C++,Class,Reference,Constants,我总是觉得我不应该使用引用来初始化类成员,因为 我不知道引用的生命周期和 如果引用值在类之外更改,则相应的类成员也将更改为新值 但是在测试了下面的代码之后,我感到困惑 class Test { public: Test(int& i) :m_i(i) {} int m_i; }; class Test3 { public: Test3(int& i) :m_i(i) {} const int& m_i; }; int main() {
class Test
{
public:
Test(int& i) :m_i(i) {}
int m_i;
};
class Test3
{
public:
Test3(int& i) :m_i(i) {}
const int& m_i;
};
int main()
{
{
std::cout << "\n// Test 1" << std::endl;
int i = 10;
Test oTest(i);
printf("oTest.i = %d\n", oTest.m_i);
i = 20;
printf("oTest.i = %d\n", oTest.m_i);
}
{
std::cout << "\n// Test 1.1" << std::endl;
int* i = new int;
*i = 10;
Test oTest(*i);
printf("oTest.i = %d\n", oTest.m_i);
*i = 20;
printf("oTest.i = %d\n", oTest.m_i);
delete i;
printf("oTest.i = %d\n", oTest.m_i);
}
{
std::cout << "\n// Test 3" << std::endl;
int i = 10;
Test3 oTest(i);
printf("oTest.i = %d\n", oTest.m_i);
i = 20;
printf("oTest.i = %d\n", oTest.m_i);
}
{
std::cout << "\n// Test 3.1" << std::endl;
int* i = new int;
*i = 10;
Test3 oTest(*i);
printf("oTest.i = %d\n", oTest.m_i);
*i = 20;
printf("oTest.i = %d\n", oTest.m_i);
delete i;
printf("oTest.i = %d\n", oTest.m_i);
}
return 0;
}
类测试
{
公众:
测试(int&i):m_i(i){}
国际货币基金组织;
};
类Test3
{
公众:
Test3(int&i):m_i(i){}
康斯坦因特&穆伊;
};
int main()
{
{
std::cout您的测试(int&i):m_i(i)
调用一个复制构造函数,并且由于您的字段是int,而不是int&,测试1和1.1始终打印原始的10
在测试3.1中,不要求访问已释放/删除的内存会产生垃圾。(有些调试编译器故意在释放的内存中放入不同的模式,但这是其调试性质的一部分。)玩具程序中的任何内容都不会更改i
指向的值,因此在一个企业计划中,你会得到一个很难找到的“”
// Test 1
oTest.i = 10
oTest.i = 10 <---- Why not 20?
// Test 1.1
oTest.i = 10
oTest.i = 10 <---- Why not 20?
oTest.i = 10 <---- Why not some garbage number?
// Test 3
oTest.i = 10
oTest.i = 20
// Test 3.1
oTest.i = 10
oTest.i = 20
oTest.i = 20 <---- Why not some garbage number?