c++ - 这是编译器错误还是我的代码?

标签 c++ g++ clang istream clang++

这是一个示例代码:

#include <iostream>
#include <stdexcept>
#include <cstring>
#include <ctime>
#include <sstream>

using std::cout;
using std::endl;

std::size_t const BUF_SIZE(1000);

std::ostream& operator<<(std::ostream& os, std::tm const& rhs)
{   
    os << asctime(&rhs);
    return os; 
}   

std::istream& operator>>(std::istream& is, std::tm& rhs)
{   
    while (is.peek() == ' ' || is.peek() == '\t')
    {   
        is.get();
    }   
    std::streampos curPos = is.tellg();
    char buf[BUF_SIZE];
    is.getline(buf, BUF_SIZE);
    char* ptr = strptime(buf, "%D %T", &rhs);
    if (ptr == 0)
    {   
        throw std::runtime_error("strptime() failed!");
    }   
    std::size_t processed = ptr - buf;
    is.seekg(curPos + static_cast<std::streampos>(processed));
    return is; 
}   

int main()
{   
    std::istringstream is("10101 07/09/12 07:30:00 123.24");
    int uuid(0);
    double price(0);
    std::tm ptime; std::memset(&ptime, 0, sizeof(tm));

    is >> uuid >> ptime >> price;
    cout << "UUID: " << uuid << endl;
    cout << "Time: " << ptime;
    cout << "Price: " << price << endl;
} 

我试图为 struct tm 重载 << 和 >> 运算符! 如果我用 g++ 编译我的代码并运行它,我得到:

UUID: 10101
Time: Sun Jul  9 07:30:00 2012
Price: 123.24

完美!

但是,如果我使用 clang++ 编译它,我会得到:

UUID: 10101
Time: Sun Jul  9 07:30:00 2012
Price: 0

糟糕!

这是怎么回事?这是 clang 的问题还是我处理 istream 的方式?

最佳答案

我能够重现这个(g++ 4.7.0 和 clang++ 3.1 与 libc++-svn)并且一个简短的调试 session 显示 clang++ 在 getline 之后设置了 eofbit(这是正常的),然后以某种方式导致 seekg 设置 failbit。这听起来像是一个错误,因为 seekg 首先清除 eofbit (§27.7.2.3/41)

要变通,请在 getlineseekg 之间的任意位置插入 is.clear()

关于c++ - 这是编译器错误还是我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10989483/

相关文章:

c++ - 在 64 位机器上编译 32 位 :/usr/bin/ld: cannot find -l<someLibs>

c++ - 符号表是否包含每个 undefined symbol 的库名称?

c++ - Xcode 4.5 和 OpenMP with Clang (Apple LLVM) 仅使用一个内核

c++ - 成员未归零,clang++ 错误?

C++ 获取 "Segmentation Fault"Linux x64 的文件名和行号

c++ - 显式删除 shared_ptr

c++ - G++ 允许在 x64 上进行隐式 long-to-int 截断

c++ - 从菜单退出游戏不起作用

c++ - 如何使用GMock检查基类函数被调用

c++ - 将 xvalue 转换为非常量左值引用时,为什么 gcc 和 clang 中的编译器错误不一致?