2

I have a string_view:

std::string_view view;

How can I append something like a const char* to it? For example:

std::string_view view = "hello";
view += " world"; // Doesn't work

Also, how can I create a string_view with a specified size? Like for example:

std::string_view view(100); // Creates a string_view with an initial size of 100 bytes
5
  • 1
    string_view is just a view. i.e. the actual object is somewhere else. So you can only 'view' using string_view. You cannot append and cannot set the size. Commented Nov 3, 2020 at 19:05
  • So what's the point of std::string_view if it is just like a char*? Commented Nov 3, 2020 at 19:08
  • It is like a char* with length. It can be used like a regular container and it is easy to pass around functions (takes one parameter instead of two i.e (char*, int)) Commented Nov 3, 2020 at 19:11
  • Is that it though? Commented Nov 3, 2020 at 19:12
  • 1
    string_view is designed to be usable in many places where a std::string can be used, but without needing to copy any data around. It is iteratable, so it can be used with other containers and algorithms that take input iterators. Sub-views can be easily created within a string_view without copying any data. It is just easier to work with than a raw char*+int pair. Commented Nov 3, 2020 at 19:18

1 Answer 1

2

std::string_view is a read-only view into an existing char[] buffer stored elsewhere in memory, or to chars that are accessible by a range of iterators. You can't add new data to a std::string_view.

For what you are attempting, you need to use std::string instead, eg:

std::string s = "hello";
s += " world";
std::string s(100, '\0');
Sign up to request clarification or add additional context in comments.

4 Comments

So what's the point of std::string_view if it is just like a char*?
string_view provide some features/safeties over using a raw pointer.
@ManUser123 Its about the size() parameter. std::string has a disadvantage that it owns the buffer, but an advantage that it knows the size(). string_view remedies this by letting the user supply the buffer while still keeping fast size() lookups.
@Mikhail it is not just about size(). string_view offers other useful features, too. Searches, comparisons, sub-string extractions without needing to allocate new string copies, etc

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.