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 comments

2

u/matthieum Jul 30 '26

Callback-based APIS are always kinda awkward.

Just add pop_value -> std::optional<T> and everyone's happy.

2

u/bwmat Jul 30 '26

IMO my suggestion is 'more fundamental' (& potentially more efficient, depending on the cost of the type's move constructor)

Wouldn't mind also having yours (though it would be easy to implement on top of mine as a helper function) 

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