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

前端 未结 2 377
春和景丽
春和景丽 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:08

    std::string is a class that stores pointers to another memory location where the actual string is stored. If you write std::string to file, only the bytes representing the pointers is written, not the string itself.

    0 讨论(0)
  • 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<T> 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...

    0 讨论(0)
提交回复
热议问题