你const應該申請多少std::map?
// Given a custom structure, really any type though
struct Foo
{
int data;
};
// What's the difference between these declarations?
const std::map<int, Foo> constMap;
const std::map<const int, const Foo> moreConstMap;
什么是權衡或之間的差異constMap和moreConstMap?
答案可能也適用于其他 stl 容器。
編輯1。
提供更多背景關系。考慮兩者之間差異的一個潛在用例可能是作用域為 .cpp 檔案的靜態查找表。讓我們說...
//Foo.cpp
namespace {
const std::map<int, Foo> constConfigMap{ {1, Foo{1}}, {2, Foo{2}} };
// vs
const std::map<const int, const Foo> moreConstConfigMap{ {1, Foo{1}}, {2, Foo{2}} };
}
void someFunctionDefinition()
{
Foo blah { constConfigMap.at(2) };
// do something with blah
}
uj5u.com熱心網友回復:
正如已經提到的,映射中的鍵是隱式常量。
將該值mymap[k] = v設為 const型別將阻止您使用,因為索引運算子將回傳對 const 的參考。您需要使用insert/emplace和erase修改地圖。
uj5u.com熱心網友回復:
std::map包含pair的{key, value}. key始終不變,您無法修改它。另一方面,value是可修改的,如果您使用const,則不是。因為const一開始的那些,任何東西都是可以修改的,所以你的問題的答案是它們完全一樣。沒有區別。
uj5u.com熱心網友回復:
存在的情況下沒有差別std::map拋開他們是不同型別的。
當宣告變數時
const,地圖類本身的狀態不能改變。只有您可以呼叫它的成員函式是 const 限定的成員函式,例如
const_iterator find( const Key& key ) const;
兩個 const 限定 find()都將回傳 a const_iterator,這將在和的情況下參考const std::pair<const int, Foo>型別物件(就像那樣operator[])。這些型別幾乎是同義詞,因為成員未宣告為。這些是不同的型別,因為它們是由不同的詞素集宣告的,可以通過以下代碼說明:constConfigMapconst std::pair<const int, const Foo>moreConstConfigMapsecondstd::pairmutable
struct Foo
{
int data;
void bar() {}
// needs to be const-qualified
bool operator==(const Foo& other) const { return data == other.data; }
};
namespace {
const std::map<int, Foo> constConfigMap{ {1, Foo{1}}, {2, Foo{2}} };
// vs
const std::map<const int, const Foo> moreConstConfigMap{ {1, Foo{1}}, {2, Foo{2}} };
}
int main() {
auto it1 = constConfigMap.find(1);
auto it2 = moreConstConfigMap.find(1);
*it1 == *it2; // error: no match for ‘operator==’
it1->second == it2->second;
it1->second.bar(); // error: passing ‘const Foo’ as ‘this’ argument discards qualifiers
// neither is ill-formed, what would happen is other question
const_cast<Foo&>(it1->second).bar();
const_cast<Foo&>(it2->second).bar();
return 0;
}
編譯器會指出那些是不同的型別。
| *it1 == *it2;
| ~~~~ ^~ ~~~~
| | |
| | pair<[...],const Foo>
| pair<[...],Foo>
您根本無法更改地圖或其元素。你不能在Foo不丟棄const.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/376898.html
上一篇:為什么嵌套宏沒有展開?
下一篇:將讀取的位元組數轉換為讀取的秒數
