本文介绍了安全地重载流操作符>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有大量资料可供重载运算子< 以模拟 toString() -style方法将复杂对象转换为字符串。我对也感兴趣实施反向, operator>> 将字符串反序列化为对象。

There's a ton of information available on overloading operator<< to mimic a toString()-style method that converts a complex object to a string. I'm interested in also implementing the inverse, operator>> to deserialize a string into an object.

通过检查 STL 源,我收集到:

By inspecting the STL source, I've gathered that:

istream &operator>>(istream &, Object &);

将是用于反序列化 Object 。不幸的是,我一直在为如何正确实现这一点 - 特别是如何处理错误:

would be the correct function signature for deserializing an object of type Object. Unfortunately, I have been at a loss for how to properly implement this - specifically how to handle errors:


  1. 如何指示无效数据流?

  2. 如果 在流中出现格式错误的数据,在返回操作符链接的引用之前,是否要重置任何标志?

  1. How to indicate invalid data in the stream? Throw an exception?
  2. What state should the stream be in if there is malformed data in the stream?
  3. Should any flags be reset before returning the reference for operator chaining?


推荐答案


  1. 如何在流中指示无效数据?引发异常?

您应该设置 fail 位。如果流的用户想要抛出异常,他可以配置流(使用 istream :: exceptions ),流将会相应地抛出。我会这样做,然后

You should set the fail bit. If the user of the stream wants exception to be thrown, he can configure the stream (using istream::exceptions), and the stream will throw accordingly. I would do it like this, then

stream.setstate(ios_base::failbit);




  1. 如果数据格式不正确, ?

对于不符合您要阅读格式的格式不正确的数据,通常应设置 fail 位。对于内部流特定错误,使用位(例如,如果没有连接到流的缓冲区)。

For malformed data that doesn't fit the format you want to read, you usually should set the fail bit. For internal stream specific errors, the bad bit is used (such as, if there is no buffer connected to the stream).


  1. 在返回操作符链接的引用之前是否应重置任何标志?

我没有听说过这样的事情。

I haven't heard of such a thing.

要检查流是否处于良好状态,可以使用 istream :: sentry 类。创建一个对象,传递流和 true (告诉它不要立即跳过空格)。如果 eof 失败,哨兵将评估为 false 位置1。

For checking whether the stream is in a good state, you can use the istream::sentry class. Create an object of it, passing the stream and true (to tell it not to skip whitespace immediately). The sentry will evaluate to false if the eof, fail or bad bit is set.

istream::sentry s(stream, true);
if(!s) return stream;
// now, go on extracting data...

这篇关于安全地重载流操作符&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:51