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*
?
CodePudding user response:
But I pass them a std::string_view object using its data() member function. Is this bad practice
Yes, this is a bad practice. It's bad primarily because a string view doesn't necessarily point to a string that is null terminated. In case it doesn't, passing data()
into a function that requires null termination will result in undefined behaviour.
Secondarily, there are cases where knowing the length of the string beforehand is more efficient. The length is known since it's stored in the string view. When you use data()
only as an argument, you're not providing the known size to the function.
Use this instead: std::istringstream iss(std::string{str});
Should I revert back to const char*?
I see no good reason for doing so in this case.