3 ms·
> The problem is that std::string is not a good type to use as a parameter for various reasons. In addition to its aggressive allocation behavior, it's also fai
by ninkendo 12y ago
> The problem is that std::string is not a good type to use as a parameter for various reasons. In addition to its aggressive allocation behavior, it's also fairly inflexible. What are the alternatives?
I think a more specific critique is that std::string is not a good type to use as a copy parameter (ie. a non-reference, non-rvalue parameter.) It's perfectly acceptable in scenarios where you're passing it as a const reference (ie. not transferring ownership) or passing it as an rvalue where it can be moved in-place.
Your critique (and suggestion to use string_ref) seems to be oriented more towards use cases where a mutated copy of a string (be it a substring or some other transformation) needs to be passed around... I don't think it's fair to say "it's not good as a parameter."
- humanrebar 12y agoNo, it's bigger than just copy parameters. std::string, even as a const reference, only works well in these cases: 1. your users already have a std::string 2. you want to support string literals 3. you'll be converting to string in the implementation anyway What if I have a vector<const char>? What if I have a type called SanitizedString or OracleString? What about character arrays retrieved from C ABI calls? And even if 3. is true, you are encoding implementation details in your interface. If you need to optimize your type later to use a trie, you'll have to do extra allocations and copies after all. My point is that interfaces should require what they need: a character sequence if they need a character sequence and a character buffer if they need a character buffer. Hence my comment about std::string being more appropriately named std::string_buffer. Even string_ref isn't perfect because it assumes your sequence is in contiguous memory. I'm hoping developments in the C++ language and standard library comes up with a good answer to that problem, perhaps one that leverages the concepts proposals. But even a concepts-based solution will have drawbacks, such as requiring even more code to go in your header file.