ken
ken

Reputation: 836

How to get a non-const iterator while using a const "this" pointer?

My problem is the use of const_cast<>. I have a class which inherits from vector. Now in one of its member functions when I use this->begin(), this being a const pointer, it returns a constant iterator but I want to obtain a non-const iterator. The code looks something like ...

class xyz : private std::vector<//something>
{
public:
 xyz();
 void doSomething();
}

void doSomething()
{
    xyz::iterator it;
    it = this->begin();
    *it.insert(something); //here is the problem and this where I need to use const_cast 
                           // and in a lot more places
}

In the above function, since this->begin() returns a const iterator, I am forced to use a constant iterator and do a typecasting whenever I need to insert an element.

I thought of using const_cast at this->begin() but my friend told me that it is a bad idea to remove the constness of the this pointer. If it is so, then what is the way around?

Upvotes: 1

Views: 1111

Answers (1)

James Kanze
James Kanze

Reputation: 154017

If the vector is part of the state of the class, either as a member or as a base (although it's really bad practice to publicly inherit from vector), then a const member function should not modify it. If the vector is part of the state, and a function modifies it, the function should not be const.

Generally. There are special cases where, for example, the vector represents cached state, that is logically calculated, but whose calculation is expensive. In such cases, you can make the vector a mutable member. But do be sure that the vector really doesn't represent "observable state".

And finally, the code you post doesn't seem to have anything to do with the problem. For starters, the only function is non-const. And the code won't compile, for several reasons (use of this in a non-member function, invocation of a member function insert on an iterator, which doesn't have such a member, etc.).

Upvotes: 2

Related Questions