【发布时间】:2018-01-02 03:08:29
【问题描述】:
根据std::mapdocumentation,它将键值对存储在std::pair<const Key, Value>中,因此map中的键是const。
现在假设我有一个std::map,其中的键是指向某些对象的指针。
struct S {};
struct Data {};
using MyMap = std::map<S*, Data>;
我们还假设有一个函数foo 接受S* 参数。
void foo(S* ptr) { /* modify the object (*ptr) */ }
现在,问题是:当我使用基于范围的 for 循环遍历 MyMap 时,我能够将 map 元素键传递给 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 的调用编译得很好,因此看起来我可以修改指向常量的指针后面的对象。
为什么我能做到?
P.S. 这里有一个live example at Coliru 说明了我的观点。为简洁起见,我使用int 而不是S 和Data。
【问题讨论】:
-
您正在制作元素的副本;你可以用那个个人副本做任何你想做的事......
-
不要将指向 const 的指针与不可变指针混淆!
-
@KerrekSB 啊,确实!工作日结束时,我的大脑让我感到困惑 :) 谢谢!
-
发生在最好的情况下:-)
标签: c++ pointers stl constants stdmap