gpt4 book ai didi

c++ - 引用传递行为及其范围

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:21:36 24 4
gpt4 key购买 nike

在下面的代码中,变量 a 通过引用传递给构造函数,由参数 x 接收。然后 x 作为对属性的引用传递。然后用值 3 初始化该属性。程序在运行时输出值 3。

我的问题

程序不应该崩溃或显示 2 因为在构造函数被调用之后x 应该超出范围并被释放,它的地址应该被释放。并试图写入它应该会导致内存访问冲突。然而在这种情况下,x 仍然在程序控制下,保存着 'a' 的地址

这是有效的 C++ 行为还是我遗漏了什么?

#include <iostream>
#include <conio.h>

using namespace std;

class myclass {

public:
int& attribute;
myclass(int& x):attribute(x) {

}

void func() {
attribute = 3;
}
};

int main() {
int a = 2;
myclass obj(a);
obj.func();
std::cout << a;
_getch();
}

最佳答案

不,这个程序很好。 attribute 是对a 的引用。 x 超出范围的事实既不在这里也不在那里。

如果您将代码更改为

myclass(int x):attribute(x)

那就麻烦了。

关于c++ - 引用传递行为及其范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615960/

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