Pedantic gcc warning:在函数返回类型上输入限定符

Set*_*son 67 c++ const gcc-warning

当我第一次使用GCC 4.3编译我的C++代码时(在成功编译它之后没有4.1,4.0,3.4的-Wall -Wextra选项的警告)我突然遇到了一堆表单错误warning: type qualifiers ignored on function return type.

考虑temp.cpp:

class Something
{
public:
    const int getConstThing() const {
        return _cMyInt;
    }
    const int getNonconstThing() const {
        return _myInt;
    }

    const int& getConstReference() const {
        return _myInt;
    }
    int& getNonconstReference() {
        return _myInt;
    }

    void setInt(const int newValue) {
        _myInt = newValue;
    }

    Something() : _cMyInt( 3 ) {
        _myInt = 2;
    }
private:
    const int _cMyInt;
    int _myInt;
};
Run Code Online (Sandbox Code Playgroud)

跑步g++ temp.cpp -Wextra -c -o blah.o:

temp.cpp:4: warning: type qualifiers ignored on function return type
temp.cpp:7: warning: type qualifiers ignored on function return type
Run Code Online (Sandbox Code Playgroud)

有人能告诉我我做错了什么违反了C++标准吗?我认为,当按价值返回时,领先const是多余的,但我无法理解为什么有必要用它生成警告.还有其他地方我应该离开const吗?

Rob*_*edy 94

它没有违反标准.这就是为什么他们是警告而不是错误.

确实你是对的 - 领先const是多余的.编译器警告你,因为你添加的代码在其他情况下可能意味着什么,但在这种情况下没有任何意义,并且它希望确保在你的返回值结果可以修改之后你不会失望.

  • 它警告而不是错误并不意味着什么.其他无效的代码,如`sizeof(void)`也只是警告,但显然是被禁止的.标准不知道警告和错误之间的区别:两者都是诊断. (17认同)
  • @litb:他说的话还是正确的.当然,他们发出警告的事实并不能保证*它不会像你说的那样违反标准,但*原因*他们被警告而不是错误是编译器实施者不想禁止它.他们不想禁止它的原因是因为它没有违反标准. (3认同)

小智 19

编译一些使用Boost.ProgramOptions的代码时遇到此警告.我使用-Werror这样警告就是杀死我的构建,但由于警告的来源是在Boost的深处,我无法通过修改我的代码来摆脱它.

经过多次挖掘后,我发现了禁用警告的编译器选项:

-Wno-ignored-qualifiers
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 我遇到了同样的问题,最后用`-isystem`而不是`-I`设置Boost的include路径,这样可以抑制Boost头引发的所有警告. (7认同)
  • @Philipp 的解决方案是正确的。使用 -Wno-ignored-qualifiers 会影响您的代码并阻止您的编译器发出您创建的警告,而 Philipp 的解决方案不会影响您自己的代码产生的警告。 (3认同)

Bra*_*him 7

仅当您返回引用或指针(在这种情况下指向常量而不是常量指针)时,返回常量值才有意义,因为调用者能够修改引用(指向)的值。

对与您的问题无关的代码的另一条评论:我认为最好使用 setter 而不是

int& getNonconstReference() {
    return _myInt;
}
Run Code Online (Sandbox Code Playgroud)

这应该是:

void setMyInt(int n) {
  _myInt = n;
}
Run Code Online (Sandbox Code Playgroud)

此外,返回对 int 的 const 引用是没有用的。对于更大的对象,其复制或移动的成本更高,这确实有意义。