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?
The simple example would be an argument to a function that is returned. The standard explicitly forbids eliding the move in this case (not that they could…):
Additionally, you can explicitly request move construction for an even simpler although a bit more artificial example:
Uhm… yet another that does not involve
std::move(it can technically be elided, but most compilers will probably not):While the optimizer can elide it by rewriting the code as:
I pretty much doubt that the compiler will actually do it. Note that in each code path the object being returned in known before
v1andv2are created, so the optimizer can locate the proper object in the return location after the rewrite.The situations where copy/move can be elided are described in 12.8/31. If you manage to write code that does not fall into those categories and the type has a move constructor, the move constructor will be called.