C & C++

C & C++

Made by DeepSource

Found copy-on-return when move-on-return is faster CXX-P2006

Performance
Major

The analyser has found a local variable that can't be automatically moved. The reason for this behavior is the constness of the variable. Consider declaring the variable without the qualifier const.

Speed improvement comes with avoiding redundant memory allocation. The compiler decides to move the return value to the caller under certain conditions.

If the variable used with the return statement is const qualified, the copy or copy-assignment constructor is used to return the value instead of the move or move-assignment constructor.

Bad practice

#include <vector>

std::vector<int> get_vector(void) {
  const std::vector<int> v {1, 2, 3};
  // Variable `v` can't be moved, as it is marked as const
  return v;
}

Recommended

#include <vector>

std::vector<int> get_vector(void) {
  std::vector<int> v{1, 2, 3};
  return v;
}