This post is about don’ts. Here are this post’s two most important rules: Don’t use std::move thoughtless and don’t slice. Let’s start.
Here are the don’ts for today.
- ES.56: Write
std::move()only when you need to explicitly move an object to another scope
- ES.60: Avoid
deleteoutside resource management functions
- ES.61: Delete arrays using
deleteand non-arrays using
- ES.63: Don’t slice
The first rule is a disguised don’t.
Most of the time, there is no need to call std::move explicitly.The compiler automatically applies to move semantics if the source of the operation is an rvalue. An rvalue is an object with no identity. An rvalue typically has no name, and you can not get its address. The remaining objects are lvalues.
Applying std::move to a lvalue gives, most of the time, an empty object. The lvalue is afterward in a so-called moved-from state. This means that it is in a valid but no nearer specified state. Sound strange? Right! You just have keep this rule in mind: After you move from a lvalue such as std::move(source) you can not make any assumption about source. You have to set it to a new value.
Wait for a second. The rule says you should only use std::move to move an object to another scope. The classical use cases are objects which can not be copied but moved. For example, you want to move a std::promise into another thread.
The function product (1) gets the std::promise by rvalue reference. A promise cannot be copied but moved; therefore, std::move is necessary (2) to move the promise into the newly created thread.
Here is the big don’t! Don’t use std::move in a return statement.
Trust your optimizer! If you return the object just by copying, the optimizer will do its job. This is a best practice until C++14; this is an obligatory rule since C++17 and is called guaranteed copy elision. Although this technique is called automatic copy elision, move operations are also optimized away with C++11.
RVO stands for Return Value Optimization and means that the compiler is allowed to remove unnecessary copy operations. What was until C++14 a possible optimization step becomes a in C++17 guarantee.
Two unnecessary copy operations can happen in these few lines—the first one in (1) and the second one in (2). With C++17, both copy operations are not allowed.
If the return value has a name, it’s called NRVO. This acronym stands for Named Return Value Optimization.
The subtle difference is that the compiler can still copy the value myValue according to C++17 (1). But no copy will take place in (2).
Okay, I can make it short. Don’t use new and delete the application code. This rule has a friendly reminder: “No naked new!”.
Here is the rationale for the last rule. Resource management in application code is error-prone.
The guidelines state in the comment: “just delete the object p”. Let me put it more drastically. This is undefined behavior!
First of all. What is slicing? Slicing means: you want to copy an object during assignment or initialization, and you get only a part of the object.
Let’s start simple.
The lines (1), (2), and (3) have all the same effect: the Derived part of d is removed. I assume that was not your intention.
In the announcement to this post, I said that slicing is one of the darkest parts of C++. Now it becomes dark.
I created a small hierarchy consisting of the Base and the Derived class. Each object of this class hierarchy should return its name. I made the method getName virtual (1) and overrode it in (2); therefore, I will have polymorphism. I can use a derived object via a reference (6) or a pointer to a base object (7). Under the hood, the object is of type Derived.
This will not hold if I just copy Derived d to Base b1 (5). In this case, slicing kicks in, and I have a Base object under the hood. In the case of copying, the declared or static type is used. The actual or dynamic type is used if you use an indirection such as a reference or a pointer.
To keep the rule in mind is quite simple: If your instances of a class should be polymorphic, it should declare or inherit at least one virtual method, and you should use its objects via an indirection such as a pointer or a reference.
Of course, there is a cure for slicing: provide a virtual clone function. Read the details here: C++ Core Guidelines: Rules for Copy and Move.
This post was about don’ts. The next post will start with a do. Use curly braces for the initialization of data.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,