Is this a valid use of const_cast?

The C ++ 11 erase()standard changed the signature of standard container methods : now they accept const_iteratorinstead of iterators. The rationale is explained in this document:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2350.pdf

Now, if one implements in a std::vector<T>simple way, you can use iterator types directly const T *and T *as const and mutable, respectively. Therefore, in the method erase()we may have the following code:

iterator erase(const_iterator it)
{
    ...
    for (; it != end() - 1; ++it) {
        // Destroy the current element.
        it->~T();
        // Move-init the current iterator content with the next element.
        ::new (static_cast<void *>(it)) T(std::move(*(it + 1))); // FAIL
    }
    ...
}

Now the problem is that since it itis a pointer to const, static rollback will fail.

it? , it const (, , const) (erase()) const.

EDIT: . .

( std::vector), . - , , , .

void * - .

+4
1

erase const, , const . , , const- const:

iterator non_const = begin() + (it - begin());

.

+6

All Articles