Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

string_view Vs const char* performance

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*?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading