简体   繁体   中英

Backwards compatability considerations when moving from const std::string& to std::string_view?

I maintain a C++ library that frequently uses const std::string& arguments in its API. However, I have received some user requests to switch over to std::string_view to help enable efficiencies that wouldn't be possible with the current API.

I am considering simply replacing all instances of const std::string& arguments with std::string_view (possibly with a feature check that verifies that std::string_view is available). Will this break backwards compatibility for any of my users? I tried the simple replacement and it didn't seem to break anything in my code or tests, but of course that's not an exhaustive check.

I do realize that this will break some code that depends on the exact function signatures for my library. For the sake of simplicity, assume that I don't allow users to depend on the exact type signatures/arguments for my functions.

I have attempted to replace std::string const& with std::string_view several times in my own code, and one of the following has always tripped me up:

  • std::string_view never owns, so if any of your std::string -based code must own the character buffers for lifetime reasons, that part of the code cannot be converted to use std::string_view . These issues can be subtle so care should be taken.
  • Based on the first point, any code that requires ownership/ std::string usage means that the efficiency gains you otherwise might have when using entirely std::string_view may not be fully realized.
  • If you rely on null-terminated strings, then std::string_view is not a good candidate. Pay close attention to any functions that might require char const* arguments, where an implicit assumption is made that the character buffer ends with '\\0' .

If you can guarantee that all of the above conditions are met, then you're probably good to go with the std::string to std::string_view migration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM