[Cs3] no except and copy elision

Mikhail Nesterenko mikhail at cs.kent.edu
Fri Feb 11 20:35:33 EST 2022


CS3 students,

Two things from the last lecture. In the example we studied:

  http://www.cs.kent.edu/~mikhail/classes/cs3/Examples/STLContainersSequential/Vectors/moveSemantics.cpp

1. The move constructor signature

     MovableClass(MovableClass&& src) noexcept {cout << "move constructor" << endl;}

   does indeed need "noexcept" or some of the STL implementations will
   not use it. The idea is that move constructor destroys the object so
   if it throws the exception while the container is in the middle
   of building a new object there is no way to back out of it.

   Here are more details on this:
   https://stackoverflow.com/questions/28627348/noexcept-and-copy-move-constructors
   
2. In the code

      MovableClass mo3 = myFunc();

   Where myFunc() returns an object of MoveableClass, it appears that
   a move or copy constructor needs to be called to take the return
   value of myFunc and construct mo3 on the basis of it.

   However, the standard allows an optimization called "copy/move
   elision": when the compiler sees that a function returns xvalue it
   is allowed to just build mo3 in-place out of it rather than copy
   from it.

   More details here: https://stackoverflow.com/questions/63683597/move-constructor-vs-copy-elision

Thanks,
--
Mikhail


More information about the cs3 mailing list