std::basic_ifstream throws std::bad_cast

試著忘記壹切 提交于 2019-12-23 20:20:52

问题


I am trying to read data from a file using below code. (Note that you need to enable C++11 features on GCC to make this compile.)

#include <fstream>

typedef unsigned char byte;

int main()
{
    std::string filename = "test.cpp";
    std::basic_ifstream<byte> in(filename, std::basic_ifstream<byte>::in | std::basic_ifstream<byte>::binary);
    in.exceptions(std::ios::failbit | std::ios::badbit);
    byte buf[5];
    in.read(buf, 5);
    return 0;
}

However, when reading data I get an exception:

terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast

This happens when the in.read(buf, 5) command is invoked.

I know that I can suppress this exception by not setting the exception mask I set but this does not fix the problem, it only masks it. Without an exception mask, the code keeps working but 0 characters are read.

Does anyone know why this exception is thrown? And how do I make it go away?


回答1:


c++ STL only contains two specializations of char_traits:

   struct char_traits < char >;
   struct char_traits <wchar_t >;

For the code posted to work a definition of char_traits<byte> is required.

More details in this SO question




回答2:


If you redefine byte as char the bad_cast exception will no longer occur.

I presume the basic_ifstream template is not fully debugged for unsigned char specialization. According to the Standard § 27.3, char_traits<CharType> need only be instantiated by the library for CharType = {char|char16_t|char32_t|wchar_t}



来源:https://stackoverflow.com/questions/17628207/stdbasic-ifstream-throws-stdbad-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!