Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

c++ - When would I pass const& std::string instead of std::string_view?

I understand the motivation for using std::string_view;
it can help avoid unecessary allocations in function arguments.

For example:
The following program will create a std::string from a string literal.
This causes an undesired dynamic allocation, as we are only interested observing the characters.

#include <iostream>

void* operator new(std::size_t n)
{
    std::cout << "[allocating " << n << " bytes]
";
    return malloc(n);
}

void observe_string(std::string const& str){}

int main(){
  observe_string("hello world"); //prints [allocating 36 bytes]
}

Using string_view will solve the problem:

#include <iostream>
#include <experimental/string_view>

void* operator new(std::size_t n)
{
    std::cout << "[allocating " << n << " bytes]
";
    return malloc(n);
}

void observe_string(std::experimental::string_view const& str){
}

int main(){
  observe_string("hello world"); //prints nothing
}

This leaves me with a question.
When would I choose std::string by const& instead of string_view for function arguments?

Looking at the interface of std::string_view, it looks as though I could replace all instances of std::string that are passed by const&. Are there any counter examples to this? Is std::string_view meant to replace std::string const& for parameter passing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When would I choose std::string by const& instead of string_view for function arguments?

Do you need a null-terminated string? If so, then you should use std::string const& which gives you that guarantee. string_view does not - it's simply a range of const char.

If you do not need a null-terminated string, and you do not need to take ownership of the data, then you should use string_view. If you do need to take ownership of the data, then it may be the case that string by value is better than string_view.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...