'Correct usage of string_view and s suffix
I would like to evaluate the following code to understand the benefits of using string_view
and s suffix.
std::string word{"apple"};
foo(word);
foo("banana");
foo("banana"s);
bar(word);
bar("banana");
bar("banana"s);
Here, foo
and bar
function prototype is as follows.
foo(const std::string& w);
bar(std::string_view w);
Comparing foo(word)
and bar(word)
.
foo(word)
: call-by-reference, no additional object is created.bar(word)
: temporarystd::string_view
object is created but does not require additional allocation or copying.
Comparing foo("")
and bar("")
.
foo("banana")
: a temporarystd::string
object is created. It requires dynamic allocation and copying.foo("banana"s)
: same as previous except the temporarystd::string
object is created more efficiently. (Any advantage of using the s suffix in C++)bar("banana")
: a temporarystd::string_view
object is created but does not require additional allocation or copying.bar("banana"s)
: a temporarystd::string
object and a temporarystd::string_view
object are created.
My conclusion is as follows: use std::string_view
instead of const std::string&
and do not use s suffix when passing a string literal. Is there anything wrong with this analysis or anything I missed?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|