r/cpp • • Jul 29 '26

const_cast: A Necessary Evil

https://www.elbeno.com/blog/?p=1858
70 Upvotes

106 comments sorted by

View all comments

Show parent comment

0

u/matthieum Jul 31 '26

I can see more efficient, but it introduces a can of worms in exchange.

Specifically, if the user-supplied callback throws an exception, is the item popped or not?

Well, given that the user may have moved out of the item, it probably should be popped. The easier way is to pop it first (move) then call the user-supplied callback -- ie, implement consume in terms of pop, making pop more fundamental.

Using a try-catch block is more straightforward and retains efficiency, but it's not compatible with -fno-exception.

Using a guard which pops in the destructor retains efficiency and is compatible with -fno-exception, but it's no longer quite as straightforward.


As for the ergonomics, callbacks are terrible, as I explained in https://www.reddit.com/r/cpp/comments/1v9zcrn/comment/p0wnjou/, due the inversion of control which results.

1

u/bwmat Jul 31 '26

Specifically, if the user-supplied callback throws an exception, is the item popped or not?

I was thinking yes(mentioned that in my original comment), and not really considering non-standard -fno-exception scenarios

1

u/bwmat Jul 31 '26

Well, given that the user may have moved out of the item, it probably should be popped.

Actually, since they might have modified it in any way, the collection's invariants are in peril, so it MUST be removed.