Consider the following mwe, implementing a simple class that overloads the multiply operator:
#include <iostream>
using namespace std;
class A {
public:
double a;
A &operator*(double b)
{
a *= b;
return *this;
}
friend A &operator*(double b, A &m) { return m * b; } // (*)
};
int main()
{
A a;
a.a = 5.0;
a * 3.0;
std::cout << a.a << std::endl;
3.0 * a;
std::cout << a.a << std::endl;
return 0;
}
It compiles and runs just fine, printing the expected output. However cppcheck gives the following warning.
tmp.cpp:15:48: error: Reference to temporary returned. [returnTempReference]
friend A &operator*(double b, A &m) { return m * b; }
When rewriting (*)
as
friend A &operator*(double b, A &m) { m * b; return m; }
The error from cppcheck disappears.
So, is this an actual problem and I'm overseeing something, or is it a false positive by cppcheck?
Some context: In my code, class A
is actually a Matrix class, for which I don't want to create a new object upon multiplying with a constant, thus returning the reference.