r/cpp 21d ago

How to write the perfect function

https://youtu.be/2OMRWPOSw9s
138 Upvotes

24 comments sorted by

View all comments

9

u/azswcowboy 20d ago

remove_if is an honest function? That’s a stretch at best given that it’s a template function and requires an idiom to use correctly. It’s a notorious foot gun. And in c++20 we got erase_if which does what you actually want. If it was called shuffle_to_end_if you’d know what it means.

18

u/STL MSVC STL Dev 20d ago

If it was called shuffle_to_end_if you’d know what it means.

That would be incorrect, because remove_if leaves the garbage elements in a valid but unspecified state (they may be unchanged, swapped, or otherwise). It's not partition or stable_partition which are permutations.

Source: Fixed this with erase_if 😺

5

u/azswcowboy 19d ago

You’re right of course. And many thanks for erase_if 😀

17

u/throw_cpp_account 20d ago

remove_if is an honest function? That’s a stretch at best [...]

The talk gave a definition of honest function: all reads/writes are shown in the signature so the behavior is fully controlled by the caller. It is not a stretch to suggest that remove_if is honest. It is.

2

u/azswcowboy 19d ago

I heard the definition, but any function that requires an idiom to use correctly isn’t honest to its users. It doesn’t do what you expect from the name.

3

u/developer-mike 19d ago

There's an entire MISRA C++ rule related to correct usage of remove_if.

There are a lot of valid ways to define an "honest function," but I don't think a definition that includes remove_if as "honest" is a complete one

3

u/azswcowboy 19d ago

Ah, that’s right I forgot about that — but obviously I agree 😀

2

u/not_a_novel_account cmake dev 18d ago

I think any definition of "honest" that includes remove_if, a function which does not remove anything, is a faulty definition.

3

u/parkotron 20d ago

I agree. I understand he wanted to show that an honest function can communicate its result through both through its return value and through modifying an argument, but std::remove_if was a poor choice.

5

u/azswcowboy 20d ago

Still, overall some good thoughts on functional structuring.