gpt4 book ai didi

c++ - 为什么当类的数据成员更改为引用时输出不同

转载 作者:行者123 更新时间:2023-11-27 22:40:28 25 4
gpt4 key购买 nike

下面的程序给出了预期的输出

#include <iostream>
#include <string>
using namespace std;
class test
{
string name; // non-referance
public:
test(string name1 = "default") :name (name1) { cout << name << " is constructed"<< endl;}
~test() { cout << name << " is destructed"<<endl;}
};
int main()
{
test t1("Mike");
test t2;
}

输出:符合预期

Mike is constructed
default is constructed
default is destructed
Mike is destructed

当数据成员“name”变为引用变量时,输出不同(当两个对象都被析构时,输出的“name”值(“Mike”和“default”)消失了,为什么?

class test 
{
string &name; // **Make it reference**
public:
test(string name1 = "default") :name (name1) { cout << name << " is constructed"<< endl;}
~test() { cout << name << " is destructed"<<endl;}
};

输出:缺少“Mike”和“default”

Mike is constructed
default is constructed
is destructed
is destrcuted

最佳答案

name1 参数是test 构造函数的本地参数。它超出范围并在 test 构造函数退出时被销毁。

name 没有被声明为引用时,它是一个实际的 string 对象,其生命周期是它包含的 test 对象的生命周期。它在初始化时从name1复制数据。因此,当稍后在 test 析构函数中使用 name 时,它仍然是一个有效的对象,拥有自己的数据,并且您会看到预期的输出。

name 被声明为引用时,它不是自己的对象,而是绑定(bind)到 name1 对象(它成为 name1),因此当 name1 被销毁时,它会悬空。因此,当稍后在 test 析构函数中使用 name 时,它不再引用有效的 string 对象,并且代码具有 < strong>未定义的行为。

使后一种情况正确工作的唯一方法是让 name1 也成为对某些外部 string 的引用,该字符串在 的生命周期内保持有效测试对象,例如:

#include <iostream>
#include <string>

using namespace std;

class test
{
string &name;
public:
test(string &name1) :name (name1) { cout << name << " is constructed" << endl; }
~test() { cout << name << " is destructed" << endl; }
};

int main()
{
string name1 = "Mike";
test t1(name1);

string name2 = "default";
test t2(name2);
}

关于c++ - 为什么当类的数据成员更改为引用时输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49440468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com