Pedantic gcc 警告:函数返回类型的类型限定符

Pedantic gcc warning: type qualifiers on function return type(Pedantic gcc 警告:函数返回类型的类型限定符)
本文介绍了Pedantic gcc 警告:函数返回类型的类型限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I compiled my C++ code with GCC 4.3 for the first time, (after having compiled it successfully with no warnings on 4.1, 4.0, 3.4 with the -Wall -Wextra options) I suddenly got a bunch of errors of the form 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 吗?

Can someone tell me what I am doing wrong that violates the C++ standard? I suppose that when returning by value, the leading const is superfluous, but I'm having trouble understanding why it's necessary to generate a warning with it. Are there other places where I should leave off the const?

推荐答案

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

It doesn't violate the standard. That's why they're warnings and not errors.

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

And indeed you're right — the leading const is superfluous. The compiler warns you because you've added code that in other circumstances might mean something, but in this circumstance means nothing, and it wants to make sure you won't be disappointed later when your return values turn out to be modifiable after all.

这篇关于Pedantic gcc 警告:函数返回类型的类型限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)