C++ Logo

sg12

Advanced search

[ub] Proposal: make self-initialized references ill-formed (C++17?)

From: John Zwinck <jzwinck_at_[hidden]>
Date: Sat, 13 Sep 2014 21:52:07 +0800
I recently happened upon some code which, boiled down to its essence, was
like this:

  for (int ii = 0; ii < 1; ++ii)
  {
    const std::string& str = str; // !!
    std::cout << str << std::endl;
  }

My to my surprise, this code compiled (and produced a segfault at runtime).
 I say surprise because I had all warnings enabled (as errors) in GCC 4.7
and 4.9, yet there was no complaint. I got a good answer from Jonathan
Wakely (http://stackoverflow.com/a/25720743/4323) explaining why GCC failed
to catch it, but this got me thinking: why does C++ allow this at all?

So, a proposal: perhaps in C++17 we could declare that self-initialized
references are ill-formed. I did consider whether this might impact
existing code; the only use case that came to mind might be SFINAE, though
I surely have never seen it used that way.

I would appreciate any thoughts on this, and hope I have come to the right
place to discuss it.

Received on 2014-09-13 15:52:30