开发者

Why no compiler enforcement in const_iterator

开发者 https://www.devze.com 2022-12-12 19:16 出处:网络
Consider the following code : #include <vector> #include <iostream> class a { public: int i; void fun() { i = 999; }

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();
  开发者_如何学Python  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 a* aa = (*iterator);

Or, this is my wrong expectation on const_iterator?


The const_iterator says that you can't modify the element in the container; 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
0

精彩评论

暂无评论...
验证码 换一张
取 消