我对在空 ostringstream
上调用 tellp
的标准行为有疑问。我有一个函数 foo,它首先调用 tellp
:
void foo(std::ostream& os)
{
std::ostream::pos_type pos = os.tellp();
// do some stuff.
}
int main()
{
std::ostringstream os;
foo(os);
}
在 Visual Studio 2005 中,使用新创建的空 ostringstream
调用此函数会导致 pos
变量被设置为无效的 pos_type
,在 Visual Studio 2005 中设置为 pos_type(_BADOFF)
。
ofstream
没有相同的行为,其中 tellp
返回 pos_type(0)
,这是一个有效的 pos_type
.
这是符合标准的行为吗?此行为与其他编译器一致吗?
最佳答案
27.6.2.4:
pos_type tellp();
Returns: if fail() != false, returns pos_type(-1) to indicate failure. Otherwise, returns rdbuf()->pubseekoff(0, cur, out).
pubseekoff 失败时返回 -1。但是我不确定为什么在 ostringstream 的情况下会发生这种情况,可能是太累了找不到关于undefined 或implementation-dependent 的词.根据我的常识,我会说对于 ostringstream 这应该给出 0,对于默认构造的 ostream -1,对于新打开文件 0 的 ostream。
关于c++ - tellp 在空 ostringstream 上的标准行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526270/