gpt4 book ai didi

c# - 从 C++ 到 C# : Never Return a Reference to a Local Object?

转载 作者:太空狗 更新时间:2023-10-29 22:34:08 24 4
gpt4 key购买 nike

在 C++ 中有一个建议:“永远不要返回对本地对象的引用”,如下引用自“C++ Primer”:

“关于返回引用,有一件至关重要的事情需要理解:永远不要返回对局部变量的引用。

“当函数完成时,分配本地对象的存储被释放。对本地对象的引用指的是函数终止后未定义的内存。考虑以下函数:

 // Disaster: Function returns a reference to a local object
const string &manip(const string& s)
{
string ret = s;
// transform ret in some way
return ret; // Wrong: Returning reference to a local object!
}

“这个函数在运行时会失败,因为它返回一个本地对象的引用。当函数结束时,ret所在的存储被释放。返回值指的是程序不再可用的内存。 "

问题:那么这仍然适用于 C# 吗?还是因为引入了 GC 而无关紧要?

最佳答案

在 .NET 中不可能返回对局部变量的引用

参见:Why doesn't C# support the return of references?

另请参阅:Ref returns and ref locals (Eric Lippert's Blog)

关于c# - 从 C++ 到 C# : Never Return a Reference to a Local Object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6563845/

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