Why does C++ reject appending a structure to a binary file if it contains a member of the string class?

前端 未结 2 376
春和景丽
春和景丽 2021-01-27 07:51

So today I made almost no progress programming because I very slowly realized that C++ is a very type-cased sensitive language in the respect that I cannot append a structure to

2条回答
  •  粉色の甜心
    2021-01-27 08:23

    Do NOT use reinterpret_cast for serialization/deserialization or stringification. reinterpret_cast is a very dangerous tool that should be used only in very particular situations. The correct way of dealing with your issue is to provide an operator<< and an operator>> for your Info class. Example:

    std::ostream& operator<<(std::ostream& os, const Info& p)
    {
        os << name;
        os << weight;
        os << grade;
        return os;
    }
    

    reinterpret_cast literally asks the compiler to look at a memory location and act as if it were a T. Classes like std::string are complicated: they own resources and store pointers to other memory locations inside them. If you attempt to write the bytes of an std::string out, you'll get garbage, as your characters are likely not stored with the std::string instance itself...

提交回复
热议问题