C++14中decltype(auto)导致CLion误报合法语句错误的问题
Let’s break down the issue step by step, just like we’d hash it out in a real dev discussion:
1. The Hidden Undefined Behavior in Your Code
When you call print_and_access4(Container<int>(5), 0), you’re passing a temporary Container<int> object (created on the fly by Container<int>(5)).
The function print_and_access4 returns decltype(auto), which here resolves to int&—since container[index] returns a T&. You then bind this reference to auto& y.
The critical problem: temporary objects get destroyed at the end of the full expression (right after the = in this line). That means y becomes a dangling reference—it points to an element of a container that no longer exists. This is undefined behavior per the C++ standard: the program might seem to run, but its behavior is unpredictable and could break in unexpected ways.
2. Why CLion Flags It But g++ Doesn’t
- CLion’s Static Analysis: CLion uses a Clang-based static checker under the hood, which is far more aggressive at catching potential dangling references and unsafe code by default. It immediately spots that you’re binding a reference to a member of a short-lived temporary, so it flags this as an error to warn you about the danger.
- g++’s Default Warning Settings: By default, g++ doesn’t enable all the strict warning flags that would catch this issue. If you compile with
-Wall -Wextra -Wdangling-reference, g++ will actually warn you about this exact problem. The fact that it compiles without errors just means the compiler didn’t reject the code (undefined behavior isn’t a mandatory compile error), not that the code is correct.
3. How to Fix This
To eliminate the dangling reference, you have two straightforward options:
- Store the container in a named variable first, so it outlives the reference:
Container<int> c(5); auto& y = print_and_access4(c, 0); - If you don’t need a mutable reference, adjust the function to return a copy of the element instead of a reference, or add a
const-qualified overload ofoperator[]and returnconst T&.
内容的提问来源于stack exchange,提问作者nakiya

