Simple demo
In order to compile this demo, I had to specify the minimum standard (C++ 17): g++ -std=c++17 demo.cpp
.
#include <string>
#include <string_view>
#include <iostream>
template<typename STR> void f(STR str) {
STR sub = str.substr(4, 3);
const char* addr_str = str.data();
const char* addr_sub = sub.data();
std::cout << "Difference between addresses: " << (addr_str - addr_sub) << std::endl;
std::cout << sub.data() << std::endl;
}
int main() {
std::string digits ("0123456789");
f<const std::string &>(digits);
f<const std::string_view&>(digits);
}
This simple demo program prints, when compiled and run on my computer:
Difference between addresses: 96
456
Difference between addresses: -4
456789
Thus, it demonstrates that std::string_view::substr()
returns a view onto the string view on which substr()
is called and the difference between their respective addresses is only 4.
Also, the char*
returned by .data()
is not null-terminated, thus, the rest of the original string is printed.
Conversely, if substr()
is called on a std::string
, it creates a new string, therefore, the difference between their addresses is larger than 4.