Pedantic gcc warning: type qualifiers on function return type

前端 未结 8 490
名媛妹妹
名媛妹妹 2020-12-08 06:07

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 opt

8条回答
  •  醉梦人生
    2020-12-08 06:31

    Returning a constant value only makes sense when you return a reference or a pointer(in this case pointer to constant and not a constant pointer) because the caller is able to modify the referenced (pointed to) value.

    Another comment on the code not related to your question: I think it's better to use a setter instead of

    int& getNonconstReference() {
        return _myInt;
    }
    

    Which will should be:

    void setMyInt(int n) {
      _myInt = n;
    }
    

    Moreover, it's useless to return a const reference to an int. It does make sense for a bigger object whose copy or move is more expensive.

提交回复
热议问题