This diagnostic rule is based on the F.49 CppCoreGuidelines rule.
The analyzer has detected a function declaration that returns values of constant type. Although the 'const' qualifier is intended to prevent modification of temporary objects, such behavior may interfere with move semantics. Costly copying of large objects results in decreased performance.
Here is a synthetic example:
class Object { .... };
const std::vector<Object> GetAllObjects() {...};
void g(std::vector<Object> &vo)
{
vo = GetAllObjects();
}
Due to the 'const' qualifier at the return type of the 'GetAllObjects' function, the compiler does not invoke the move assignment operator but chooses the copy assignment operator when selecting the 'operator=' overload. In fact, it copies the vector of objects returned by the function.
To optimize the code, simply delete the 'const' qualifier.
class Object { .... };
std::vector<Object> GetAllObjects() {...};
void g(std::vector<Object> &vo)
{
vo = GetAllObjects();
}
Now, when the 'GetAllObjects' function is called, the return vector of objects is moved.
Note that this diagnostic rule applies only to code written in C++11 or newer versions. This behavior is based on move semantics that was introduced in C++11.
Let's look at the following code (custom type implementation for long arithmetic):
class BigInt
{
private:
....
public:
BigInt& operator++();
BigInt& operator++(int);
BigInt& operator--();
BigInt& operator--(int);
friend const BigInt operator+(const BigInt &,
const BigInt &) noexcept;
// other operators
};
void foo(const BigInt &lhs, const BigInt &rhs)
{
auto obj = ++(lhs + rhs); // compile-time error
// can't call operator++()
// on const object
}
This approach was used in the past when move semantics was not yet implemented in C++, and one wanted to prevent accidental access to a temporary object.
If you return a non-constant object from the overloaded 'operator+', you can call the overloaded prefix increment operator on a temporary object. Such semantics is forbidden for built-in arithmetic types.
Starting with C++11, the code can be fixed using ref-qualifiers of non-static member functions, and the compiler can be allowed to apply move semantics:
class BigInt
{
....
public:
BigInt& operator++() & noexcept;
BigInt& operator++(int) & noexcept;
BigInt& operator--() & noexcept;
BigInt& operator--(int) & noexcept;
friend BigInt operator+(const BigInt &,
const BigInt &) noexcept;
// other operators
};
void foo(const BigInt &lhs, const BigInt &rhs)
{
auto obj = ++(lhs + rhs); // compile-time error
// can't call BigInt::operator++()
// on prvalue
}