gpt4 book ai didi

c++ - 通过引用传递,仅限子范围?

转载 作者:行者123 更新时间:2023-11-28 01:41:34 28 4
gpt4 key购买 nike

我已尝试搜索此问题,因为我敢打赌已经有类似的问题了。但是,我只获得有关在全局环境中通过引用传递的主题。

我想知道以下问题;


变量作用域只在这个函数中,离开作用域时会被清除

void Class::DoSomething(){
String s = "localVariable";

cout << s;
}

如果我要更改以下两个函数中的优先函数。范围是否也仅在父函数中,变量内存是否会被释放,或者我是否必须调用 free()?

void Class::DoSomethingParent(){
String s = "localVariable"; //Local scope only

//This function uses the reference of my variable s.
Class::DoSomethingChild(s);

//Does the prior function do anything special because of the reference,
//so I have to call free(s)?

//Or does the variable still gets freed after leaving the scope of this function?
}
void Class::DoSomethingChild(String& value){
cout << value;
}

最佳答案

在 C++ 中具有自动存储持续时间的对象本质上是在功能 block 范围内声明的对象,该范围拥有控制生命周期在其中创建的此类对象。示例:

void function(){
....
String s = "Some Data";
someFuncByReference(s);
....
} //All objects of automatic storage duration owned by this scope are destroyed here...

无论您是通过引用传递对象还是获取对象的地址,然后传递给函数。被调用的函数 someFuncByReference 仍然无法控制 s 的生命周期,并且不应破坏 s1

这适用于任何“函数”,包括非成员函数成员函数函数特化 由模板生成。请注意,这与类的数据成员 不同。类数据成员的生命周期由该类的构造函数和析构函数控制。


1:但是,如果这样做,它必须使用 placement-new 创建另一个。

关于c++ - 通过引用传递,仅限子范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911441/

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