std::string_view has made it to C++17 and it is widely recommended to use it instead of const std::string&.
One of the reasons is performance.
Can someone explain how exactly std::string_view is/will be faster than const std::string& when used as a…
string_view was a proposed feature within the C++ Library Fundamentals TS(N3921) added to C++17
As far as i understand it is a type that represent some kind of string "concept" that is a view of any type of container that could store something…
Since C++17, we have std::string_view, a light-weight view into a contiguous sequence of characters that avoids unnecessary copying of data. Instead of having a const std::string& parameter, it is now often recommended to use…
There is an implicit conversion from std::string to std::string_view and it's not considered unsafe, even though this surely may cause a lot of dangling references if the programmer is not careful.
On the other hand, there's no implicit conversion…
Compiling with gcc-7.1 with the flag -std=c++17, the following program raises an error:
#include
void foo(const char* cstr) {}
void bar(std::string_view str){
foo(str);
}
The error message is
In function 'void…
I understand the motivation for using std::string_view;
it can help avoid unecessary allocations in function arguments.
For example:
The following program will create a std::string from a string literal.
This causes an undesired dynamic…
Is there a safe standard way to convert std::string_view to int?
Since C++11 std::string lets us use stoi to convert to int:
std::string str = "12345";
int i1 = stoi(str); // Works, have i1 = 12345
int i2 = stoi(str.substr(1,2));…
I have a method that takes std::string_view and uses function, which takes null terminated string as parameter. For example:
void stringFunc(std::experimental::string_view str) {
some_c_library_func(/* Expects null terminated string */);
}
The…
I know that a trivial std::string_view is not guaranteed to be null-terminated. However, I don't know if a std::string_view literal is guaranteed to be null-terminated.
For example:
#include
using namespace std::literals;
int…
I'm writing a c++ parser for a custom option file for an application. I have a loop that reads lines in the form of option=value from a text file where value must be converted to double. In pseudocode it does the following:
while(not EOF)
…
Our team is working with a 10+ years old C++ code base and recently switched to a C++17 compiler. So we are looking for ways to modernize our code. In a conference talk on YouTube I heard the suggestion, to replace const char* global strings with…
Consider a method that returns a std::string_view either from a method that returns a const std::string& or from an empty string. To my surprise, writing the method this way results in a dangling string view:
const std::string&…