gpt4 book ai didi

来自方法的 C++ 引用变量

转载 作者:行者123 更新时间:2023-12-03 08:22:42 25 4
gpt4 key购买 nike

这样做有意义吗:

class SomeClass
{
public:
static Object getObject()
{
return Object("example")
}
};

int main()
{
const Object& myObject = SomeClass::getObject();

// do something with myObject
}

或者这与只是获取对象一样
const Object myObject = SomeClass::getObject();

?

最佳答案

从 Herb Sutter 关于此主题的文章中,可以找到 here ,两种情况都是正确的:

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error.



但是如果你删除 const从情况1开始,就不行了。

关于来自方法的 C++ 引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60060199/

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