gpt4 book ai didi

c++ - stringstream 可以在读取原语时抛出异常吗?

转载 作者:可可西里 更新时间:2023-11-01 15:55:48 27 4
gpt4 key购买 nike

查看一些旧代码,我们有很多类似以下内容:

// This is dumb
string do_something(int in)
{
stringstream out;
try
{
out << std::fixed << in;
}
catch(std::exception &e)
{
out << e.what();
}

return out.str();
}

// Can't we just do this? Can this ever fail?
string do_something_better(int in)
{
stringstream out;
out << std::fixed << in;
return out.str();
}

当 stringstream 读取原语时,它会抛出异常吗?读取字符串时怎么办?

最佳答案

总结几个答案

默认情况下,流不会抛出异常。如果启用,他们可以。

stringstream out;
out.exceptions(std::ios::failbit); // throw exception if failbit gets set

根据 Apache C++ Standard Library User's Guide

The flag std::ios_base::badbit indicates problems with the underlying stream buffer. These problems could be:

Memory shortage. There is no memory available to create the buffer, or the buffer has size 0 for other reasons (such as being provided from outside the stream), or the stream cannot allocate memory for its own internal data, as with std::ios_base::iword() and std::ios_base::pword().

The underlying stream buffer throws an exception. The stream buffer might lose its integrity, as in memory shortage, or code conversion failure, or an unrecoverable read error from the external device. The stream buffer can indicate this loss of integrity by throwing an exception, which is caught by the stream and results in setting the badbit in the stream's state.

Generally, you should keep in mind that badbit indicates an error situation that is likely to be unrecoverable, whereas failbit indicates a situation that might allow you to retry the failed operation.

所以看起来最安全的方法是

string do_something(int in)
{
stringstream out; // This could throw a bad_alloc
out << std::fixed << in; // This could set bad or fail bits

if(out.good())
{
return out.str();
}
else
{
return "";
}
}

虽然根据 Handling bad_alloc 这有点矫枉过正如果创建流失败,则需要担心更大的问题,程序可能会退出。因此,假设它已经通过创建流,那么设置 badbit 是可能的,但极不可能。 (流分配内存 < sizeof(int))。

也不太可能设置 failbit(不确定用于读取堆栈的用例,而不是损坏的堆栈)。所以下面的代码就足够了,因为此时从流错误中恢复是不可能的。

string do_something(int in)
{
stringstream out;
out << std::fixed << in;
return out.str();
}

关于c++ - stringstream 可以在读取原语时抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com