Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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

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

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

The function is suppose to return byte array to indicate binary data. However, the function is returning std::string. My guess is that, the author is trying to avoid from perform explicit dynamic memory allocation.

I try to verify the output is correct.

int main()
{
    unsigned char data[3];
    data[0] = 0; data[1] = 1; data[2] = 2;
    std::string encoded_string = base64_encode(data, 3);
    // AAEC
    std::cout << encoded_string << std::endl;


    std::string decoded_string = base64_decode(encoded_string);
    for (int i = 0; i < decoded_string.length(); i++) {
        // 0, 1, 2
        std::cout << (int)decoded_string.data()[i] << ", ";
    }
    std::cout << std::endl;
    getchar();
}

The decoded output is correct. Just want to confirm, is it valid to std::string to hold binary data, to avoid manual dynamic memory management.

std::string s;
s += (char)0;
// s.length() will return 1.
question from:https://stackoverflow.com/questions/4655206/is-it-valid-to-use-stdstring-to-hold-binary-data-to-avoid-manual-dynamic-mem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...