Why does std :: istream :: getline not work on std :: string?

In C ++ istream

has a method called getline

that works on an array of C-style characters. I know there are other independent functions getline

that work with istream

and a std::string

. But why a separate method? Why not put it in istream

? And why does istream

getline only work on C-style strings instead std::string

?

+3


source to share


2 answers


I think the string library and thread library were developed separately. I think this is why we don't have universal support std::string

in the threading library. Although this has been considered a bit, it std::fstream::open

now accepts strings.

It should be noted that it is std::istream::getline

more secure than std::getline

that, so in some situations this should be preferred.



The problem is std::getline

not checking the length of the string to be read. This means that malicious code (or a corrupted data source) can explode memory by presenting data containing a very long string.

With std::istream::getline

you have a limit on how much you can read.

+2


source


My point is that it is designed to improve performance. You can only allocate a block of buffer once, and it can iteratively process line by line. Note that std::getline

which takes std::string

as an argument is called s.erase()

before writing to s

, and this may result in s

more buffer allocation if the line is too long.



+1


source







All Articles