Search code examples
c++stringmemorystring-view

Adding const char* to string_view


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

Solution

  • 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');