From 9024fc99af36affd3feae16113d54f6a92c1b006 Mon Sep 17 00:00:00 2001 From: Jens Maurer Date: Sat, 23 Mar 2024 08:04:34 +0100 Subject: [PATCH] P2748R5 Disallow Binding a Returned Glvalue to a Temporary --- source/basic.tex | 2 -- source/statements.tex | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/source/basic.tex b/source/basic.tex index 6d24c315b9..23b118f308 100644 --- a/source/basic.tex +++ b/source/basic.tex @@ -4532,8 +4532,6 @@ persists until the completion of the full-expression containing the \grammarterm{expression-list}. -\item The lifetime of a temporary bound to the returned value in a function \tcode{return} statement\iref{stmt.return} is not extended; the temporary is destroyed at the end of the full-expression in the \tcode{return} statement. - \item A temporary bound to a reference in a \grammarterm{new-initializer}\iref{expr.new} persists until the completion of the full-expression containing the \grammarterm{new-initializer}. \begin{note} This might introduce a dangling reference. diff --git a/source/statements.tex b/source/statements.tex index f2cfe2cd27..a6693a7afe 100644 --- a/source/statements.tex +++ b/source/statements.tex @@ -905,6 +905,29 @@ before the destruction of local variables\iref{stmt.jump} of the block enclosing the \tcode{return} statement. +\pnum +In a function whose return type is a reference, +other than an invented function for \tcode{std::is_convertible}\iref{meta.rel}, +a \tcode{return} statement that binds the returned reference to +a temporary expression\iref{class.temporary} is ill-formed. +\begin{example} +\begin{codeblock} +auto&& f1() { + return 42; // ill-formed +} +const double& f2() { + static int x = 42; + return x; // ill-formed +} +auto&& id(auto&& r) { + return static_cast(r); +} +auto&& f3() { + return id(42); // OK, but probably a bug +} +\end{codeblock} +\end{example} + \rSec2[stmt.return.coroutine]{The \keyword{co_return} statement}% \indextext{\idxcode{co_return}}% \indextext{coroutine return|see{\tcode{co_return}}}%