Is a std::string_view parameter better than a const char* one in the code below?
void func( const std::string_view str )
{
std::istringstream iss( str.data( ) ); // str is passed to the ctor of istringstream
std::size_t pos { };
int num { std::stoi( str.data( ), &pos, 10 ) }; // and here it's passed to std::stoi
}
int main()
{
std::array<char, 20> buffer { };
std::cin.getline( buffer.data( ), 20 );
func( buffer.data( ) );
}
Both std::istringstream ctor and std::stoi require a const std::string& as their parameter. But I pass them a std::string_view object using its data() member function. Is this bad practice? Should I revert back to const char*?
std::string_view's documentation, specifically its constructors' documentation, and taking a moment to think what it means, for the constructor to work that way. Based solely on the public specifications of the constructors of all the objects referenced in the shown code it should be fairly straightforward to determine what's happening, and whether or not there is any improvement by avoiding the use ofstring_viewand passing a plain pointer instead. Have you tried working everything out, like this, with pen and paper?std::string{str}instead ofstr.data( )for constructingstd::istringstream iss. You are constructing astd::stringin both cases, butstr.data()will cause problems if there is no null-terminating byte.