Skip to main content
added 362 characters in body
Source Link
Steve Jessop
  • 280.7k
  • 40
  • 473
  • 709

Use the iterator constructor:

std::string my_std_string(my_txt, my_txt + my_txt_len); 

This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. 

In your example, though, it doesn't make any difference, because all of the values in your array are within the range 0 to CHAR_MAX. So it's guaranteed that those values are represented the same way in char as they are in unsigned char, and hence that reinterpreting them is the same as converting them. If you had values greater then CHAR_MAX then implementations are allowed to treat them differently.

Use the iterator constructor:

std::string my_std_string(my_txt, my_txt + my_txt_len); 

This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. In your example, though, it doesn't make any difference.

Use the iterator constructor:

std::string my_std_string(my_txt, my_txt + my_txt_len); 

This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. 

In your example, though, it doesn't make any difference, because all of the values in your array are within the range 0 to CHAR_MAX. So it's guaranteed that those values are represented the same way in char as they are in unsigned char, and hence that reinterpreting them is the same as converting them. If you had values greater then CHAR_MAX then implementations are allowed to treat them differently.

Source Link
Steve Jessop
  • 280.7k
  • 40
  • 473
  • 709

Use the iterator constructor:

std::string my_std_string(my_txt, my_txt + my_txt_len); 

This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast. That would be perfectly clean, since what you say is exactly what is done. In your example, though, it doesn't make any difference.