[英]warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
[英]Why does this compiler warning only show for int but not for string? "type qualifiers ignored on function return type"
我對使用 mingw64 編譯 C++11 代碼時收到的一些警告有點困惑。 這是我的 MWE:
class A{
const string name;
const int ID;
public:
A(string name_, int ID_) : name(name_), ID(ID_){
// initialize non-const members
}
const string getName() const{return name;}
const int getID() const{return ID;}
};
int main()
{
A aObj = A("Aname", 1);
std::cout << "getName() = " << aObj.getName() << std::endl;
std::cout << "getID() = " << to_string(aObj.getID()) << std::endl;
}
代碼執行得很好並且做它應該做的,但是我得到這個編譯器警告:
,,localtest.cpp:10:9: 警告:在 function 返回類型上忽略類型限定符
[-Wignored-qualifiers] const int getID() const{return ID;}
所以警告只顯示getID()
而不是getName()
,即使兩者具有相同的類型限定符。 有人可以向我解釋一下,為什么這個警告似乎只顯示string
而不是int
? 我想這與int
作為原始數據類型有關 - 但究竟是什么?
std::string
是一個 class ,它的成員函數可以是常量。 如果你有一個常數 object 的 class 你可以只應用常數成員函數。
至於像int
這樣的基本類型,那么限定符 const 對返回值沒有意義,因為在任何情況下您都無法更改返回值。
這是一個演示程序
#include <iostream>
#include <string>
template <typename T>
const T f( const T &t )
{
return t;
}
int main()
{
std::cout << f( std::string( "Hello World!" ) ).length() << '\n';
// Invalid assignment
// f( 10 ) = 20;
return 0;
}
程序 output 是
12
如您所見,您可以將常量成員函數應用於std::string
類型的返回 object (但您不能應用非常量成員函數)。 而且您不能更改int
類型的返回值。
考慮以下:
struct MyType {
void foo() const;
void bar();
};
MyType getMutable();
const MyType getConst();
int main() {
getMutable().foo(); // fine
getMutable().bar(); // fine
getConst().foo(); // fine
getConst().bar(); // Not allowed!
}
int
沒有任何等價物。 您可以對int
RValue 執行的一組操作與const int
RValue 完全相同。 這就是您收到冗余警告的原因。
見[expr.type] :
如果prvalue最初具有類型“cv T”,其中T是cv-unqualified non-class,non-array類型,則表達式的類型在任何進一步分析之前調整為T。
本質是:你可以有const
class 或數組類型的表達式,但不能有const
原始類型的表達式。
由於int
不是 class,因此返回類型為rvalue
就足以防止對返回的 object 進行任何和所有修改。 因此,
getInt(20) = 500;
不會是可編譯的代碼,並且沒有可以在int
類型的對象上調用的成員。 這就是為什么 const 限定內置類型作為返回值沒有意義,編譯器會警告你。
但不同班級的情況有所不同。
getString("string").clear();
可能是有效或無效代碼,取決於getString
返回非 const 還是 const std::string
object,因此編譯器在后一種情況下不會發出警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.