gpt4 book ai didi

c++ - 为什么在这个例子中可以返回临时对象?

转载 作者:行者123 更新时间:2023-11-30 02:20:32 27 4
gpt4 key购买 nike

char*[] 对象可以通过 const 引用传递给函数 version2() 和 version 3(),这意味着 s2 是一个临时对象,等于“###”或“@” @@”。

但为什么临时对象s2可以返回,而临时对象temp不能。

int main()
{
result = version2(input, "###");
cout << "Your string enhanced: " << result << endl;

result = version3(input, "@@@");
cout << "Your string enhanced: " << result << endl;
return 0;
}

// No Error
const string & version2(string & s1, const string & s2)
{
return s2;
}

// Error
const string & version3(string & s1, const string & s2)
{
string temp = s2 + s1 + s2;
return temp;
}

最佳答案

重点是object life time .

对于第一种情况,正如你所说,一个临时的 std::string 被创建并传递给 version2(被绑定(bind)到参数 s2)。临时对象将在完整表达式之后被销毁,即整个 result = version2(input, "###");。这意味着 version2 返回的引用仍然有效,可以将其用于分配给 result

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created,

对于第二种情况,在version3 中创建了一个本地对象temp,它会在离开version3 时销毁。这意味着 version3 将始终返回悬空引用。并使用它分配给 result 导致 UB。编译器可能会给出诊断;但不必做。

关于c++ - 为什么在这个例子中可以返回临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49570890/

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