c++ - 迂腐的 gcc 警告 : type qualifiers on function return type

标签 c++ constants gcc-warning

当我第一次使用 GCC 4.3 编译我的 C++ 代码时(在使用 -Wall -Wextra 选项成功编译它并且在 4.1、4.0、3.4 上没有警告之后)我突然明白了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;
};

运行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

谁能告诉我我做错了什么违反了 C++ 标准?我想当按值返回时,前导 const 是多余的,但我无法理解为什么需要用它生成警告。还有其他地方我应该去掉 const 吗?

最佳答案

它不违反标准。这就是为什么它们是警告而不是错误

确实你是对的——前面的 const 是多余的。编译器会警告您,因为您添加了在其他情况下可能有意义的代码,但在这种情况下没有任何意义,并且它希望确保您稍后在返回值最终变成可修改时不会感到失望。

关于c++ - 迂腐的 gcc 警告 : type qualifiers on function return type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134237/

相关文章:

C++0x lambda 按值捕获总是 const?

c++ - 即使启用了 Wextra,gcc 也不会给出比较无符号整数 < 0 的警告

c++ - 使用自定义 QGraphicsItem 类进行 QT 碰撞检测

c++ - 使用 C++ sqlite 将特定输入插入数据库

c++ - 错误:将 ‘const ComplexNumber’ 作为 const ComplexNumber& ComplexNumber::operator-=(const Complex) 的 ‘this’ 参数传递

c - 为什么在使用 gcc C 将 uint32 转换为 uint8 时没有警告

c++ - gcc size_t 和 sizeof 算术转换为 int

c++ - make 中对 `main' 的 undefined reference

对象本身作为参数的对象上的 C++ 调用方法

c++ - 可变含义逻辑常量是否存在任何强制机制?