You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何临时对象s2可返回而temp不可?const引用传参相关疑问

Why Returning the Temporary-Bound s2 Is Safe, But Returning temp Isn’t?

Let’s break down the key differences between these two scenarios in plain terms:

1. The temporary bound to s2 gets its lifetime extended

When you pass a string literal like "###" to a function that takes a const std::string& parameter:

  • A temporary std::string object is created from the literal.
  • This temporary is bound to the const reference parameter s2.
  • According to C++ rules, if you return this const reference from the function, the temporary’s lifetime is extended to match the lifetime of the variable you assign the return value to (in your code, that’s result).

So in your main function:

result = version2(input, "###");

The temporary std::string created for "###" sticks around until result goes out of scope (at the end of main), so using result is completely safe.

2. A temporary temp created inside the function doesn’t get this extension

If you create a temporary object inside the function (like a local std::string temp = "some value";), even if you bind it to a const reference, its lifetime only lasts until the function finishes executing.

For example:

const std::string& bad_version(const std::string& input) {
    std::string temp = input + " enhanced";
    return temp; // Unsafe!
}

Here, temp is a local object that’s destroyed the moment the function returns. Returning a reference to it gives you a dangling reference—using it can cause crashes, garbage output, or other unpredictable behavior.

Even if temp is an inline temporary:

const std::string& worse_version(const std::string& input) {
    return input + " enhanced"; // Also unsafe!
}

The temporary created by input + " enhanced" is destroyed right after the function exits, leaving the returned reference pointing to nothing.

The core rule difference

  • Temporaries created as function arguments and bound to const references have their lifetime extended to the caller’s scope when returned via const reference.
  • Temporaries created inside the function (either as local objects or inline expressions) are destroyed when the function exits—any references to them become invalid immediately.

Example Safe vs. Unsafe Functions

Safe version (matches your version2):

const std::string& version2(const std::string& input, const std::string& s2) {
    // s2 is bound to the temporary created from "###"
    return s2; // Safe: temporary lives until result goes out of scope
}

Unsafe version with temp:

const std::string& bad_version(const std::string& input) {
    std::string temp = input + " enhanced"; // Local temp
    return temp; // Unsafe: temp dies when function ends
}

内容的提问来源于stack exchange,提问作者Guodong Hu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:13:36