skip to content

In C++, why do `decltype(x)` and `decltype((x))` differ, and how does `decltype(auto)` make `return (local);` return a dangling reference?

level: seniorimportance: should knowfreq 45%

answer

  1. name versus expression
  2. lvalue expression gives T&
  3. decltype(auto) keeps reference-ness
  4. parentheses in return

basics

~20 s

decltype of a plain name gives the variable's declared type, but a parenthesized name is an lvalue expression, so decltype((x)) is int&. decltype(auto) applies that rule to return (local);, returning a reference to a dead local.

solid answer

~40 s

`decltype` has two modes. For an unparenthesized name or member access it yields the entity's declared type, so `decltype(x)` is `int`. For any other expression it encodes the value category: lvalue gives `T&`, xvalue `T&&`, prvalue `T`; `(x)` is an lvalue expression, so `decltype((x))` is `int&`. `decltype(auto)` deduces by applying `decltype` to the initializer or returned expression, which is useful for forwarding: returning `limits_.at(sym)` yields `double&` where `auto` would copy. But `return (local);` deduces a reference to a local that dies at return, which is undefined behaviour to use. Since C++23 a returned move-eligible name is an xvalue, so the type becomes `double&&` instead of `double&`; it dangles either way. Clang warns with `-Wreturn-stack-address`.

code

cpp · 23 lines
cpp
#include <cstdio>
#include <map>
#include <string>
#include <type_traits>

std::map<std::string, double> g_limits{{"ES", 5.0}};

decltype(auto) limit_ref(const std::string& sym) { return g_limits.at(sym); }   // double&
auto limit_copy(const std::string& sym) { return g_limits.at(sym); }            // double
auto limit_trailing(const std::string& sym) -> decltype(g_limits.at(sym)) {     // double&
    return g_limits.at(sym);
}

int main() {
    int x = 0;
    static_assert(std::is_same_v<decltype(x), int>);
    static_assert(std::is_same_v<decltype((x)), int&>);
    static_assert(std::is_same_v<decltype(limit_ref("ES")), double&>);
    static_assert(std::is_same_v<decltype(limit_copy("ES")), double>);
    static_assert(std::is_same_v<decltype(limit_trailing("ES")), double&>);
    limit_ref("ES") = 6.0;                    // writes through the reference
    std::printf("%.1f\n", g_limits["ES"]);   // 6.0
}

go deeper

for a junior

Recall that decltype(name) is the declared type, while decltype of an expression like (x) adds a reference for lvalues.

for a middle

Explain decltype's two modes and how decltype(auto) differs from auto for a function returning a reference.

for a senior

Use decltype(auto) only for forwarding returns, ban parenthesized returned names, and pin reference-returning APIs with static_assert across -std levels.

for a principal

Weigh whether decltype(auto) belongs in public interfaces at all, given that its result changes with the body and, as C++23 shows, with the standard.

## Two questions `decltype` can answer `decltype(E)` reports a type without evaluating `E`, and the draft gives it two distinct jobs depending on the **form** of `E`: - if `E` is an **unparenthesized name** (an id-expression) or an unparenthesized class member access, `decltype(E)` is the **declared type of the entity**: `decltype(x)` for `int x` is `int`, `decltype(a->px)` is the member's declared type; - otherwise `E` is treated as an **expression**, and its value category is encoded: an lvalue gives `T&`, an xvalue gives `T&&`, a prvalue gives `T`. `(x)` is not an unparenthesized name, it is an lvalue expression, so `decltype((x))` is `int&`. The draft's own example shows the member case: with `const A* a`, `decltype(a->x)` is `double` while `decltype((a->x))` is `const double&`. ## `decltype(auto)`: deduce with decltype's rules C++14's `decltype(auto)` deduces a variable or return type by applying `decltype` to the initializer or to the returned expression. That makes it the tool for **forwarding a reference unchanged**, which plain `auto` cannot do because it drops references: | Return declaration | `return limits_.at(sym);` gives | |---|---| | `auto` | `double`, a copy | | `decltype(auto)` | `double&`, `at` returns an lvalue | | `auto ... -> decltype(limits_.at(sym))` | `double&`, the C++11 trailing form | In a trading gateway, a risk-limit accessor written with `decltype(auto)` lets a caller adjust `limit_ref("ES") = 6.0;` in place. ## The parentheses that create a dangling reference The same sensitivity to form is dangerous with locals: ```cpp decltype(auto) bad() { double local = 1.0; return (local); // not a plain name any more } ``` `return local;` would deduce `double`. `return (local);` deduces from the parenthesized expression, and the function returns a **reference to a local** whose lifetime ends at the closing brace. Any use of the result is undefined behaviour. Apple clang 21 warns with "reference to stack memory associated with local variable 'local' returned [-Wreturn-stack-address]". The exact reference type changed in **C++23**. C++23 made a returned, move-eligible name an xvalue (the "simpler implicit move" rule, recorded in the compatibility annex as "decltype(auto) f(int&& x) { return (x); } // returns int&&; previously returned int&"). So under `-std=c++23` `bad()` returns `double&&`, and under C++14 to C++20 it returns `double&`; a `static_assert` expecting `double&` fails only in C++23 mode. Either way it dangles. ## `decltype` never evaluates its operand The operand of `decltype` is an **unevaluated operand**: nothing in it runs. `decltype(g_limits.at("XX"))` is `double&` even though calling `at` with that key would throw, and `decltype(make_order())` names `Order` without constructing one. That is what makes `decltype` usable in declarations and return types. The expression rules then give a compact summary of value categories: | Expression `E` | `decltype(E)` | |---|---| | `x` (a name, declared `int x`) | `int` | | `(x)`, `*p` (lvalues of type `int`) | `int&` | | `std::move(x)` (an xvalue) | `int&&` | | `x + 1`, `make_order()` (prvalues) | `int`, `Order` | ## Trailing return types A **trailing return type** puts the return type after the parameters, `auto f(params) -> type`. Before C++14's return type deduction, it was the only way to name a type that depends on the parameters, because the parameters are in scope after `->` but not before the function name: ```cpp template<class Book> auto best(Book& b, const std::string& sym) -> decltype(b.at(sym)); ``` It is still useful when a declaration in a header must state its return type exactly while the body lives elsewhere, and for lambdas (`[](int x) -> long { ... }`). Template deduction for the `Book` parameter is its own subject; here only the return type matters. ## Habits that keep `decltype(auto)` safe 1. Use `decltype(auto)` for returns that **forward** another call's result, typically in wrappers, never for returning locals. 2. Never parenthesize a returned name in a `decltype(auto)` function. 3. Prefer plain `auto` when a value is intended; reach for `decltype(auto)` only when preserving reference-ness is the point. 4. Pin important types with `static_assert(std::is_same_v<decltype(f(...)), double&>)` so a refactor or a `-std` change cannot alter them silently. 5. Remember that `decltype(auto)` must stand alone: the draft rejects `decltype(auto)* p = &i;` and adding `const` or `&` around it, because the declared type is then "not plain decltype(auto)". Use `auto*`, `const auto&` or an explicit type in those positions.

  • What does `decltype(auto) x = (i);` deduce for `int i`, compared with `auto x = (i);`?
    `decltype(auto)` applies `decltype` to the initializer `(i)`, an lvalue expression, so `x` is `int&` and refers to `i`. Plain `auto` ignores the parentheses' value category and deduces `int`, a copy. The draft's own example lists exactly these two lines.
  • When is a trailing return type still needed after C++14?
    When the return type must be stated in a declaration without the body, for example a header declaration whose type depends on parameters, `auto f(T& t) -> decltype(t.get());`, and when a lambda needs a return type different from what its `return` statements would deduce. Return type deduction only works where the body is visible.

  • Parentheses around a name never change what decltype reports.
  • decltype(auto) and auto deduce the same return type.
  • return (local); in a decltype(auto) function returns a copy.
  • C++23 fixed the dangling reference by moving the local out.
  • decltype evaluates its operand to find the type.

Assumes C++23; since C++23 a parenthesized returned local deduces T&& under decltype(auto), where C++14 to C++20 deduced T&.