AUTOSAR C++14 Rule A12-8-4
Move constructor shall not initialize its class members and base classes using copy semantics
Since R2020b
Description
Rule Definition
Move constructor shall not initialize its class members and base classes using copy semantics.
Rationale
In C++, move operations transfer the ownership of resources rather than duplicating the
resources themselves from a source object to a target object. Because move constructors do
not duplicate resources, these constructors are faster than copy constructors. Consider this
code where the object CopyTarget
is copy-constructed and the object
MoveTarget
is move-constructed from the object
Source
.
class BigData{ //... BigData(BigData&&){ //Move Constructor //... } copy constructed BigData(const BigData&){ //Copy Constructor //... } private: std::map<int, std::string> BigBook; }; int main(){ BigData Source; BigData CopyTarget = Source; BigData Movetarget = std::move(Source); //... }
When copy-constructing CopyTarget
, the compiler duplicates the
resource Source::BigBook
from Source
to
CopyTarget
. After the copy-construction, both of these objects have a
copy of the resource BigBook
. When move-constructing
Movetarget
, the compiler transfers the ownership of the resource
Source::BigBook
to MoveTarget
. Because
move-construction does not duplicate the resource physically, it is faster than
copy-construction.
Move-construction is an optimization strategy. You expect that move-construction is cheaper and faster than copy-construction. Copy-initializing data members and base classes can make a move constructor slow and inefficient, which reduces program performance. Developers expect that move-construction uses move semantics only. Unexpectedly using copy semantics in move constructors might introduce resource leaks and inconsistency in future development. When authoring move constructors, initialize data members and base classes by using move semantics. You can copy-initialize scalar data members without violating this rule.
You might use std::move()
to implement move semantics in your code.
When you use std::move()
to move objects, declare the objects or data
members without the qualifier const
. For more information, see AUTOSAR C++14 Rule A18-9-3
.
Polyspace Implementation
When a move constructor does not use move semantics to initialize nonscalar data members and base classes, Polyspace® flags its declaration. For instance, if a move constructor initializes the base class by using the default constructor instead of the move constructor, Polyspace flags the declaration of the move constructor.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Special member functions |
Category: Required, Automated |
Version History
Introduced in R2020b