简体   繁体   English

为什么在const_iterator中不执行编译器

[英]Why no compiler enforcement in const_iterator

Consider the following code : 考虑以下代码:

#include <vector>
#include <iostream>

class a {
public:
    int i;
    void fun() { i = 999; }
    void fun() const { std::cout << "const fun" << std::endl; }
};

const a* ha() {
    return new a();
}

int main()
{
    std::vector<a *> v;
    v.push_back(new a());

    // cannot convert from 'const a *' to 'a *'
    // a* test = ha();

    std::vector<a *>::const_iterator iterator = v.begin();
    for (; iterator != v.end(); ++iterator) {
        // No enforcement from compiler? I do not want user to modify the content through
        // const_iterator.
        a* aa = (*iterator);
        aa->fun();
    }

    std::cout << (*(v.begin()))->i << std::endl;
    getchar();
}

May I know why I didn't get compiler error from 我可以知道为什么我没有从编译器中得到错误吗

a* aa = (*iterator);

I wish compiler will tell me I need to use the const_iterator in the following way : 我希望编译器告诉我我需要通过以下方式使用const_iterator:

const a* aa = (*iterator);

Or, this is my wrong expectation on const_iterator? 还是这是我对const_iterator的错误期望?

The const_iterator says that you can't modify the element in the container; const_iterator表示您不能修改容器中的元素。 that is, if you have a container of pointers, you can't change the pointer . 也就是说,如果您有一个指针容器,则不能更改该指针

You aren't changing the pointer, you're changing the object pointed to by the pointer. 您没有更改指针,而是在更改指针指向的对象

If you try to assign a new pointer to that element in the container, it will fail to compile: 如果您尝试为容器中的该元素分配一个新的指针,它将无法编译:

*iterator = new a; // < Won't compile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM