Bug 109538 - Spurious -Werror=dangling-reference false positive
Summary: Spurious -Werror=dangling-reference false positive
Status: RESOLVED DUPLICATE of bug 108165
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 13.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
Keywords: diagnostic
Depends on:
Reported: 2023-04-17 23:35 UTC by Sam Varshavchik
Modified: 2023-04-18 00:55 UTC (History)
0 users

See Also:
Known to work:
Known to fail:
Last reconfirmed:


Note You need to log in before you can comment on or make changes to this bug.
Description Sam Varshavchik 2023-04-17 23:35:33 UTC
gcc 13.0.1 would like to register a complaint:

t.C:17:14: error: possibly dangling reference to a temporary [-Werror=dangling-reference]
   17 |   const int &v=optional_arg_or(def, 0);
      |              ^
t.C:17:31: note: the temporary was destroyed at the end of the full expression ‘optional_arg_or(def, 0)’
   17 |   const int &v=optional_arg_or(def, 0);
      |                ~~~~~~~~~~~~~~~^~~~~~~~


#include <optional>
#include <utility>

const int &optional_arg_or(std::optional<int> &def,
			   int &&def_val)
  def = def_val;

  return *def;

int gimme()
  std::optional<int> def;

  const int &v=optional_arg_or(def, 0);

  int bologna=v;
  return bologna;

Changing optional_arg_or's parameter to "int def_val" silences the complaint. gcc appears to be voicing an objection that optional_arg_or returns a reference to a temporary that gets created during the function call and destroyed at the conclusion of the function call. However that temporary gets placed into a std::optional, and then a reference to the std::optional gets returned.
Comment 1 Andrew Pinski 2023-04-17 23:41:45 UTC
I suspect this will be closed as a dup of bug 108165 really. Because the warning is doing it is expected of it and it is hard to figure out without the full code available at the time (which the warning does not take that into account). It just knows the function declaration rather than what is inside the function itself.
Comment 2 Sam Varshavchik 2023-04-18 00:55:15 UTC
Eh, I'll just close it myself, this is clearly the same bug.

*** This bug has been marked as a duplicate of bug 108165 ***