警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符

warning: type qualifiers ignored on function return type [-Wignored-qualifiers]

本文关键字:类型 返回类型 -Wignore 警告 函数      更新时间:2023-10-16

我正在尝试使用 GCC 编译器编译以下代码

class Class
{
public:
uInt16    temp;
const uInt32 function() const;
}
inline const uInt32 class::function() const
{
return temp;
}

我收到以下编译器警告

警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符

任何想法如何解决此警告?

简单使用:

uInt32 function() const;

返回 const 基元类型是没有用的,因为即使没有const也无法执行c.function()++

返回 const Object 用于模仿原语并禁止类似于上面的代码, 但是现在(从 C++11 开始(,如果需要,我们可以干净地禁止它:

struct S
{
S& operator ++() &;
S& operator ++() && = delete;
};
S f(); // Sufficient, no need of const S f() which forbids move

返回类型上的const类型限定符不起作用。事实上,您的function会返回一份temp.调用方将决定此值是否必须为 const:

const auto val = Class{}.function(); // here, val is const
auto val = Class{}.function(); // here val is not const

例如,如果要返回对类成员的引用,则const类型限定符是有意义的。比较:

int f() { /* ... */ } // return int
const int& f() { /* ... */ } // return const reference to an int