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是多余的.编译器警告你,因为你添加的代码在其他情况下可能意味着什么,但在这种情况下没有任何意义,并且它希望确保在你的返回值结果可以修改之后你不会失望.
小智 19
编译一些使用Boost.ProgramOptions的代码时遇到此警告.我使用-Werror这样警告就是杀死我的构建,但由于警告的来源是在Boost的深处,我无法通过修改我的代码来摆脱它.
经过多次挖掘后,我发现了禁用警告的编译器选项:
-Wno-ignored-qualifiers
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
仅当您返回引用或指针(在这种情况下指向常量而不是常量指针)时,返回常量值才有意义,因为调用者能够修改引用(指向)的值。
对与您的问题无关的代码的另一条评论:我认为最好使用 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 引用是没有用的。对于更大的对象,其复制或移动的成本更高,这确实有意义。