Is it valid, to use std::string to hold binary data, to avoid manual dynamic memory management

后端 未结 5 1793
醉话见心
醉话见心 2021-02-05 00:55

Pay attention to base64_decode in http://www.adp-gmbh.ch/cpp/common/base64.html

std::string base64_decode(std::string const& encoded_string)


        
相关标签:
5条回答
  • 2021-02-05 01:37

    I dont think one should use std::string for byte-data-storage. The method provide aren't design to deal with byte-data and you will risk yourself since any changes (or "optimization") on std::string will break your code.

    0 讨论(0)
  • 2021-02-05 01:43

    You need an array of character( not string) to store the binary data. Best is use vector.

    0 讨论(0)
  • 2021-02-05 01:50

    I don't think it's completely valid. Care must be taken with string and binary data because it uses internally char type and char depends in the implementation if it is defined as unsigned or signed type. I prefer to use basic_string<unsigned char> and be sure of what i'm reading.

    0 讨论(0)
  • 2021-02-05 01:55

    Yes, you can store any sequence of char in a std::string. That includes any binary data.

    0 讨论(0)
  • 2021-02-05 01:57

    Yes. std::string can hold any char value ('\0' has no special meaning). However I wouldn't be surprised finding some C++ functions (e.g. from external libraries) having problems with strings with embedded NULs.

    Anyway I don't understand what you are going to gain with an std::string instead of std::vector<unsigned char> that would make your intentions more clear and that offers more guarantees (e.g. that all the bytes are in contiguous not-shared memory so that you can pass &x[0] to someone expecting a plain buffer for direct access).

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