相关疑难解决方法(0)

为什么不修改关联容器的键?

我知道在关联容器中更改对象的键是一个可怕的想法,但我想知道标准的确切位置禁止我这样做.考虑:

#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!
}
Run Code Online (Sandbox Code Playgroud)

我认为上述内容应该是非法的,但我现在正在阅读标准一段时间,而且我找不到任何真正使其成为非法的内容.它在哪里?或者它是否隐藏在未来的缺陷报告中?

c++ std language-lawyer c++11

8
推荐指数
1
解决办法
335
查看次数

标签 统计

c++ ×1

c++11 ×1

language-lawyer ×1

std ×1