问题描述
我知道在关联容器中更改对象的键是一个可怕的想法,但我不知道标准在哪里禁止我这样做。请考虑:
I know that it's a terrible idea to change the key of an object in an associative container, but I wonder where exactly the standard forbids me to do so. Consider:
#include <map>
#include <memory>
struct X { int i; };
struct lt
{
bool operator()( const std::shared_ptr< X >& lhs,
const std::shared_ptr< X >& rhs ) const
{
return lhs->i < rhs->i;
}
};
int main()
{
std::map< std::shared_ptr< X >, int, lt > m;
auto x = std::make_shared< X >();
x->i = 1;
m.insert( std::make_pair( x, 2 ) );
x->i = 42; // change key wrt the container!
}
我假设上述但我现在正在阅读标准一段时间,我找不到任何实际上使 是非法的。它在哪里?
I assume that the above should be illegal, but I was reading the standard for some time now and I can't find anything that actually makes it illegal. Where is it? Or is it hiding in a future defect report?
推荐答案
这会在程序中注入未定义行为,如果您以某种方式修改值
This injects Undefined Behavior in your program if you modify the values in a way that the comparison of any two keys is different after the change according to the comparator you specified.
根据C ++ 11标准的第23.2.4 / 3节([ associative.reqmts]):
Per Paragraph 23.2.4/3 of the C++11 Standard ([associative.reqmts]):
这篇关于为什么不修改关联容器的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!