Overriding TextBuffer::on_insert requires const_cast
For an application I'm trying to change the behaviour of a Gtk::TextBuffer
when text is inserted. I do this by overriding on_insert
, which looks like this:
void TextBuffer::on_insert(const iterator& position, const Glib::ustring& text, int bytes);
In some cases, text needs to be inserted at a different place. I do this by creating a new iterator in my overriden on_insert
, and then calling TextBuffer::on_insert
. This results in warnings on the cmdline saying that an invalidated iterator is used. The warning appears after my on_insert
call returns, so it seems Gtk(mm) reuses the same iterator afterwards.
The documentation says
Note that if your handler runs before the default handler it must not invalidate the pos iter (or has to revalidate it).
However, since the iterator is const
it is not possible to update it. I do notice that the default on_insert
handler does indeed update the iterator, so apparently works around its constness somehow.
It turns out the warning disappears when I update the iterator using a const_cast, doing this:
void MyTextBuffer::on_insert(const iterator& position, const Glib::ustring& text, int bytes)
{
const iterator new_position = ...;
TextBuffer::on_insert(new_position, text, bytes);
const_cast<iterator&>(position) = new_position; // <-- necessary to delete warning
}
I have two questions, which could be bugs:
- Why is the iterator that is given to the on_insert method reused after on_insert returns (even though there are no signals connected to signal_insert) ? -- is that intended or a bug? If it is intended it might be good to document that.
- Since the iterator is const, how can a class that overrides
on_insert
or connects to signal_insert update it?