Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::basic_ifstream throws std::bad_cast

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?

like image 782
Chris Avatar asked Jul 13 '13 07:07

Chris


2 Answers

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

like image 169
suspectus Avatar answered Sep 28 '22 02:09

suspectus


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}

like image 32
Mike Kinghan Avatar answered Sep 28 '22 02:09

Mike Kinghan