C ++ Boost io流,错误处理

时间:2022-09-06 16:36:54

Is it possible to make a custom stream work like the stanadrd ones in regard for errors? That is by default use the good/fail/bad/eof bits rather than exceptions?

是否可以使自定义流像stanadrd那样处理错误?默认情况下使用good / fail / bad / eof位而不是异常?

The boost docs only mention throwing an std::failure for stream errors and letting other error propagate (eg a badalloc from trying to allocate a buffer), however the boost code does not seem to catch these, instead relying on the user code to handle them, but all my existing code relies on the good(), bad() etc methods and the clear() method in cases where it needs to try again after an error.

boost文件只提到为流错误抛出std ::失败并让其他错误传播(例如,尝试分配缓冲区的badalloc),但是升级代码似乎没有捕获这些,而是​​依赖于用户代码来处理它们,但我的所有现有代码依赖于good(),bad()等方法和clear()方法,如果它需要在发生错误后再次尝试。

1 个解决方案

#1


From http://www.trip.net/~bobwb/cppnotes/lec08.htm

The error state can be set using:

可以使用以下命令设置错误状态:

void clear(iostate = 0);

void clear(iostate = 0);

The default value of zero results in ios_base::goodbit being set.

默认值为零会导致ios_base :: goodbit被设置。

clear();

is therefore equivalent to

因此相当于

clear(0);

which is equivalent to

这相当于

clear(ios_base::goodbit);

Note that ios_base::goodbit is a non-zero value. clear() might be used to set one of the other bits as part of a programmer's code for operator>>() for a particular object. For example:

请注意,ios_base :: goodbit是一个非零值。 clear()可用于将其他位之一设置为程序员代码的一部分,用于特定对象的operator >>()。例如:

if (bad_char) is.clear(ios_base::badbit); // set istream's badbit

if(bad_char)is.clear(ios_base :: badbit); //设置istream的badbit

#1


From http://www.trip.net/~bobwb/cppnotes/lec08.htm

The error state can be set using:

可以使用以下命令设置错误状态:

void clear(iostate = 0);

void clear(iostate = 0);

The default value of zero results in ios_base::goodbit being set.

默认值为零会导致ios_base :: goodbit被设置。

clear();

is therefore equivalent to

因此相当于

clear(0);

which is equivalent to

这相当于

clear(ios_base::goodbit);

Note that ios_base::goodbit is a non-zero value. clear() might be used to set one of the other bits as part of a programmer's code for operator>>() for a particular object. For example:

请注意,ios_base :: goodbit是一个非零值。 clear()可用于将其他位之一设置为程序员代码的一部分,用于特定对象的operator >>()。例如:

if (bad_char) is.clear(ios_base::badbit); // set istream's badbit

if(bad_char)is.clear(ios_base :: badbit); //设置istream的badbit