C & C++

C & C++

Made by DeepSource

Unnecessary expensive copy of loop-based variable CXX-P2004

Performance
Major

The for-loop's range declaration variable is copied in every iteration when it's a non-reference type. Consider using a const reference for range declaration variable.

The use of a for-range-based loop copy may cause a performance issue, as it creates a copy of the object in every iteration. The copy constructor of the class is called for each element in the range, leading to increased memory usage and decreased performance. Instead, it is recommended to use a reference to the object, to avoid unnecessary copy.

A trivially copyable type is one that can be safely copied and moved using memcpy and memmove. This means that the type has a trivial copy constructor, a trivial copy assignment operator, and a trivial destructor. Examples of trivially copyable types include:

  • Scalar types (e.g int, float)
  • POD (Plain Old Data) types (e.g. structs and arrays containing only trivially copyable types)
  • Pointers to trivially copyable types

A class or struct is considered a POD type if it is trivially copyable and satisfies certain other constraints such as having no user-defined constructors, no private or protected non-static data members, no virtual functions, and no virtual base classes.

Any object is expensive to copy if it's non-trivally copyable.

Bad practice

std::vector<std::string> keys = {"while", "for", "int"};
for (auto i: keys) { // not referencing the elements of `keys` results is expensive copy of elements
  // no modification to the key
  i.find('x');
}

Recommended

std::vector<std::string> keys = {"while", "for", "int"};
for (const auto& i: keys) { //
  // no modification to the key
  i.find('x');