Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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. 
like image 509
Cheok Yan Cheng Avatar asked Jan 11 '11 07:01

Cheok Yan Cheng


People also ask

Should I use std :: string?

h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type. Pros: When dealing exclusively in C++ std:string is the best way to go because of better searching, replacement, and manipulation functions.

Does std :: string allocate?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.


2 Answers

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

like image 184
CB Bailey Avatar answered Sep 19 '22 18:09

CB Bailey


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).

like image 22
6502 Avatar answered Sep 22 '22 18:09

6502