根據std::map
documentation,它將鍵值對存儲在std::pair<const Key, Value>
中,因此映射中的鍵是常量。爲什麼我可以將std :: map的鍵傳遞給期望非const的函數?
現在想象一下,我有一個std::map
其中鍵是指向某些對象的指針。
struct S {};
struct Data {};
using MyMap = std::map<S*, Data>;
讓我們也假設有一個允許S*
參數的函數foo
。現在
void foo(S* ptr) { /* modify the object (*ptr) */ }
,問題是:當我遍歷MyMap
與範圍爲基礎的循環,我能夠在地圖元素鍵傳遞到foo
:
MyMap m = getMyMapSomehow();
for (auto elem : m)
{
static_assert(std::is_const<decltype(elem.first)>::value, "Supposed to be `const S*`");
foo(elem.first); // why does it compile?
}
所以,儘管我static_assert
成功(所以我假設elem.first
的類型是const S*
),調用foo
編譯得很好,因此看起來好像我能夠修改pointer-to-const後面的對象。
爲什麼我能夠做到這一點?
P.S.這是一個live example at Coliru,說明了我的觀點。爲簡潔起見,我使用int
而不是S
和Data
。
您正在製作該元素的副本;你可以做任何你想要的個人副本... –
不要混淆const指針和不可變指針! –
@KerrekSB啊,的確如此!我的工作日結束時,我的大腦讓我感到困惑:)謝謝! –