[Bug c++/102704] NRVO for throw expression

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Oct 13 08:43:56 GMT 2021


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102704

Jonathan Wakely <redi at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
     Ever confirmed|0                           |1
             Status|UNCONFIRMED                 |NEW
   Last reconfirmed|                            |2021-10-13

--- Comment #2 from Jonathan Wakely <redi at gcc dot gnu.org> ---
[class.copy.elision] p1:
This elision of copy/move operations, called copy elision, is permitted in the
following circumstances (which may be combined to eliminate multiple copies):
-- in a return statement [...]
-- in a throw-expression (7.6.18), when the operand is the name of a
non-volatile object with automatic storage duration (other than a function or
catch-clause parameter) that belongs to a scope that does not contain the
innermost enclosing compound-statement associated with a try-block (if there is
one), the copy/move operation can be omitted by constructing the object
directly into the exception object
-- in a coroutine [...]
-- when the exception-declaration of an exception handler [...]


The slightly confusing "does not contain the innermost enclosing
compound-statement" means you can't elide if the throw is in a try-block and
the variable was defined outside it.

So this cannot be elided:

void f()
{
  mytype x;
  try {
    throw x;
  } catch (int) {
  }
}

But this can be:

void g()
{
  try {
    mytype x;
    throw x;
  } catch (int) {
  }
}

And the example in comment 0 can be.


More information about the Gcc-bugs mailing list