I'm trying to learn move semantics well enough to introduce it to my students. I've been using highly simplified vector- or string-like classes that manage memory and whose members output messages to demonstrate their activity. I'm trying to develop a simple set of examples to show students.
Construction elision for RVO and elsewhere in gcc 4.7 and clang aggressively eliminates copy and move construction, so while I can easily see move assignment at work, the only time I've seen move construction at work is if I turn off construction elision in gcc 4.7 with -fno-elide-constructors.
An explicit copy construction statement
MyString newString(oldString);
will invoke the copy constructor even if elision is enabled. But something like
MyString newString(oldString1 + oldString2);
doesn't invoke the move constructor because of the elision.
Anything explicitly using std::move won't make a simple example because explaining std::move has to come later.
So my question: Is there a simple code example that will invoke move construction even if copy/move constructors are being elided?
std::move
... – Mooing Duckstd::move
is how you move things explicitly. Move support is primarily about explicit moves, since most implicit moves can be caught with elision. You're doing anyone who's learning from this a disservice by hidingmove
from them. – Nicol BolasoldString1+oldString2
triggers a copy (no optimization here), but the copy is moved intonewString
(optimization). In practice, this is hard to trigger because the compiler chooses the "copy elision" optimization over the "move the copy" optimization (with good reason). – André Caron