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

Is it legal to construct std::string_view from empty vector<char>?


I have read some questions and documentation, and I guess answer is yes, since string_view will never touch the pointed to stuff, but I am a still bit confused if this is legal:

std::vector<char> v;
std::string_view sv(v.data(), v.size());

note:

  1. I know that constructor that just uses v.data() and does strlen will crash, I am asking about this particular way of constructing std::string_view.
  2. I know that constructed string_view is "evil", e.g. doing std::cout << sv.data() is UB, but I think std::cout << sv; should work

Full example:

#include <vector>
#include <iostream>
#include <string_view>

std::vector<char> v;
auto get_sv() {
std::string_view sv(v.data(), v.size());
return sv;
} 

int main() {
    std::cout << "|" << get_sv() << "|" << std::endl;

}

Solution

  • This looks perfectly legal to me.

    According to basic_string_view( const CharT* s, size_type count );

    1. Constructs a view of the first count characters of the character array starting with the element pointed by s.

    and std::vector::data() states:

    Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty (data() is not dereferenceable in that case).

    and

    Notes
    If size() is 0, data() may or may not return a null pointer.

    So depending on the implementation, the underlying char array exists at the time of printing, or the string_view was built with a nullptr. In either case it is a valid range.