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

181 views Asked by At

In C++, istream has a method called getline which operate on a C-style character array. I know there are other independent getline functions which operate on an istream and a std::string. But why a separate method? Why not put it in istream? And why does istream's getline only work on C-style strings instead of std::string?

2

There are 2 answers

0
Sarfaraz Nawaz On

My thought is that it is designed for performance reason. You can allocate a block of buffer just once, and could iteratively process line-by-line. Note that std::getline which takes std::string as argument, calls s.erase() before writing to s and it may cause s to allocate more buffer if the line is too long.

0
Galik On

I think the strings library and the streams library were developed separately. I think that is why we don't have universal std::string support in the streams library. Although that has been addressed a little but with std::fstream::open now taking strings.

One thing to note is that std::istream::getline is more secure than std::getline so should be preferred in some situations.

The problem is std::getline has no checking on the length of string that will be read. That means malicious code (or a corrupt data source) can blow the memory by presenting data containing a very long line.

With std::istream::getline you have a limit on how much can be read.