https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89757
Bug ID: 89757
Summary: accepts returning with reference to temporary in
constant expression
Product: gcc
Version: 8.3.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: leni536 at gmail dot com
Target Milestone: ---
g++ accepts this ill-formed code:
constexpr const int& foo(int x, int y) {
const int& z = x+y;
return z;
}
constexpr int&& bar(int x, int y) {
int&& z = x+y;
return static_cast<int&&>(z);
}
int main() {
constexpr int a = foo(1,2);
constexpr int b = bar(1,2);
return a+b;
}
This is invalid because both foo and bar return with a reference to a local
temporary object and expressions containing UB when evaluated are not constant
expressions.
$ g++ -std=c++14 -Wall -Wextra -pedantic -o gcc_bug gcc_bug.cpp && ./gcc_bug;
echo $?
6
Note: I tested it on 8.3.0 on my own machine, but it seems to be the same for
all versions on godbolt.