C++ and coverity issues

4.8k Views Asked by At
MyClass* const Func(const std::string& statename)

for this coverity is giving the error

Parse warning (PW.USELESS_TYPE_QUALIFIER_ON_RETURN_TYPE) type qualifier on return type is meaningless .

Do we really need to remove the const here.?

3

There are 3 best solutions below

2
On

You don't need to remove the const to get working code, but the code would most certainly be better without the pointless const. That's what the "warning" word in front of the "error" says, too.

3
On

The const in the return type (MyClass* const) is indeed completely pointless. At the same time, it does no harm other than making the code more verbose. I personally would remove it.

To understand why it's pointless, consider the following:

MyClass* p = Func(statement);

What difference did the const make?

In other words, returning T* const is conceptually no different to returning const int.

5
On

The warning is correct. The MyClass* const is not needed. It should be MyClass* simply. However, you don't need to remove it, but you should remove it.

The reason is, theoretically MyClass* const would prevent the return value of Func() from being edited. But that is anyway not editable even without const, as it's not an lvalue.See the demo here. So with/without const, the compiler will always generate error, for an attempt to modify the return value of Func().