3

Which of one of these is best suited for managing a character buffer that can be easily converted to std::string and passed to and used ( i.e. read / write ) in C functions

std::vector<unsigned char> 
std::vector<char>
karimjee
  • 41
  • 3

4 Answers4

4

char's signedness depends on the compiler.1

It can represent a unsigned char or signed char. Which type is used when representing a string is dependent on the compiler - therefore you should use char for portability, and clarity. If that isn't enough, would the less typing needed when writing char convince you? :)

Again, the compiler thinks strings are of type char *, which can be equivalent to unsigned char * or signed char *. If you're going to be working with strings use std::vector<char>.

1 char is the only type with this behavior.


References

1 Is char signed or unsigned by default?

Community
  • 1
  • 1
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
2

char is more compatible with strings than unsigned char. String literals are char[] and std::string is actually std::basic_string<char>.

Mark Ransom
  • 286,393
  • 40
  • 379
  • 604
  • In what way could unsigned char not be compatible with strings? In other words can you illustrate for me what could go wrong if I use unsigned char to represent strings? I am not disputing your answer I just want to get a better understanding – karimjee Sep 09 '11 at 02:17
  • @karimjee : `std::string` is a typedef for `std::basic_string`; `std::basic_string<>` relies on `std::char_traits<>`, but `std::char_traits<>` is only specialized for `char` and `wchar_t`. So, `std::basic_string<>` will not **portably** play nice with `unsigned char` out of the box (though in practice, it will work just fine with most modern compilers). – ildjarn Sep 09 '11 at 02:27
  • @ildjarn: you posted the best answer to the OP's original question – J T Sep 09 '11 at 02:54
0

Both are equally well suited. If these are character buffers, as opposed to bytes, I would go with std::vector< char >.

You can create a string from a vector of any of those types with std::string( v.begin(), b.end() );

K-ballo
  • 78,684
  • 20
  • 152
  • 166
0

char, unsigned char, and signed char are 3 distinct types.

  • Use an unsigned char or a signed char when dealing with numbers.
  • Use a regular char when dealing with strings.

Thus, you should use a char.

Marlon
  • 19,321
  • 11
  • 64
  • 96