std::getline() returns

三世轮回 提交于 2019-11-28 17:53:41
Charles Anderson

The istream returned by getline() is having its operator void*() method implicitly called, which returns whether the stream has run into an error. As such it's making more checks than a call to eof().

Updated:

I had mistakenly pointed to the basic_istream documentation for the operator bool() method on the basic_istream::sentry class, but as has been pointed out this is not actually what's happening. I've voted up Charles and Luc's correct answers. It's actually operator void*() that's getting called. More on this in the C++ FAQ.

Luc Hermitte

Charles did give the correct answer.

What is called is indeed std::basic_ios::operator void*(), and not sentry::operator bool(), which is consistant with the fact that std::getline() returns a std::basic_istream (thus, a std::basic_ios), and not a sentry.

For the non believers, see:

Otherwise, as other have already said, prefer the second form which is canonical. Use not fail() if really you want a verbose code -- I never remember whether xxx.good() can be used instead of !xxx.fail()

I would stick with the first form. While the second form may work, it is hardly explicit. Your original code clearly describes what is being done and how it is expected to behave.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!