为什么std :: set.insert()返回一个非const迭代器,但是我不能修改它? [英] Why does std::set.insert() return a non-const iterator, and yet I cannot modify it?

查看:412
本文介绍了为什么std :: set.insert()返回一个非const迭代器,但是我不能修改它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此代码示例:

#include <set>
#include <string>

using namespace std;

set<string> string_set;

void foo(const string& a)
{
    pair<set<string>::iterator, bool> insert_result = string_set.insert(a);

    string& val = *(insert_result.first);
    val += " - inserted";
}

因此,正确性放在一边,例如不检查是否成功插入等,这个代码看起来应该允许我在插入后修改字符串,但编译器(VS2010)禁止解引用迭代器到一个非常量字符串(我们正在从VS2005迁移这个通过没有警告)。

So, correctness aside, such as not checking for successful insertion and so on, this code looks like it should allow me to amend the string after insertion, but the compiler (VS2010) forbids dereferencing the iterator to a non-const string (we're migrating from VS2005 which waved this through without a warning).

现在,我知道这应该被禁止,因为它可能会使字符串不唯一,我很高兴它这样工作,但在现实世界的情况下,它不是相当清楚的,因为我想修改不可变的数据成员,不参与等价测试或排序。

Now, I know this should be forbidden since it may make the string non-unique, and I'm kind of glad it works this way, but in the real world case it's not quite so clear cut as that, as I want to amend a non-mutable data member that doesn't participate in equivalence testing or ordering.

我想知道的是,编译器如何不允许这样做,我怎么知道没有参考文档(这没有提到这一点)?

What I want to know is, how does the compiler KNOW I'm not allowed to do this, and how do I know without reference to the documentation (which doesn't mention this anyway)?

干杯,
Guy

Cheers, Guy

推荐答案

因为根据标准,通过
a 不允许设置<> :: iterator 。特别是标准
允许 set<> :: iterator set<> :: const_iterator
相同类型。虽然它不要求它们是相同的
类型,但它需要 set<> :: iterator的 value_type to
be const

Because according to the standard, modifications through a set<>::iterator are not allowed. The standard specifically allows set<>::iterator and set<>::const_iterator to be the same type. And although it doesn't require them to be the same type, it does require the value_type of set<>::iterator to be const.

,对
值的任何修改都可以使 std :: set<> 的不变量无效。

这篇关于为什么std :: set.insert()返回一个非const迭代器,但是我不能修改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆