ros2/rclcpp

Use string_view for non-owning string references

oysstu opened this issue · 3 comments

Feature request

Currently, the API uses const std::string & for non-owning references to strings (e.g., topic names, node names). A more modern solution would be to use string_view. String constants can be declared as string_view in a header without initializing them in every translation unit. They are also constexpr, which can potentially open up some compile-time usage.

Feature description

The blocker for implementing this right now is that the rcl layer expects null-terminated strings. It's not possible to know if the byte following the string_view buffer is a null byte or simply uninitialized memory, so one would have to copy the data to a string anyway.

Right now, I don't see how this is viable without modifying the rcl API to accept string + length parameters. I thought I'd make the issue regardless, as from a pure C++ API standpoint, using string_views would perhaps be better.

I think since we are C++17, there isn't anything blocking this from a compiler perspective. As you mention, we make pretty heavy use of null-terminated strings in the RCL and RMW layers. Changing that would be invasive, though not impossible.

I wonder if an alternative would be to look into something like this SO Answer suggests and create a zstring_view that allows string_view to be used with null-terminated strings?

The other thing here is that I've heard a lot of horror stories about the lifetimes of string_view, and how it is super easy to create dangling references (i.e. https://medium.com/@stackyjoe/yet-another-gripe-about-std-string-view-87fe1ee7a45e). So I'd want to make sure we aren't getting into those situations.

@oysstu is this something that would be potentially interested in prototyping so we could come up with concrete recommendations and identify any issues as @clalancette mentions?