Search code examples
c++c++17string-view

container of string_view's - are they always null-terminated?


Let us give any data structure containing objects of std::string_view:

std::vector<std::string_view> v{ "abc", "def" };
std::deque<std::string_view> d{ "abc", "def" };
std::set<std::string_view> s{ "abc", "def" };

Is it guaranteed by cpp standard, that these containers store objects of class std::string_view which point to the string literals ended with null?

I mean is it safe to write code like this:

void foo(const char* ptr) {
    printf("%s", ptr);
}

for (auto elem : v)
    foo(elem.data());

for (auto elem : d)
    foo(elem.data());

for (auto elem : s)
    foo(elem.data());

Solution

  • Yes, this is safe.

    In general std::string_views don't have to be null-terminated, but here you explicitly initialized them with null-terminated strings.

    The compiler is not allowed to remove null-terminator from a string based solely on the fact that it's assigned to a string_view.

    The only case when it would be allowed to do so is if it didn't change the program behavior (the as-if rule), meaning you don't need to worry about it.