3

Is iterator a propper conversion between basic_strings? Is this safe/legal? Does this create a valid string?

std::u16string str16;
//str16 is set here;
std::string cStr(str16.cbegin(), str16.cend());

In VS 2013 it seem to work ok.

EOG
  • 1,677
  • 2
  • 22
  • 36
  • 6
    This will not convert your string to another encoding, just copy it element by element. If your str16 contains code units that do not fit into `char`, they will be truncated. – n. m. could be an AI May 24 '14 at 20:47
  • related, not exact duplicate: [convert between string, u16string, u32string](http://stackoverflow.com/questions/7232710/) – quetzalcoatl May 24 '14 at 20:50

1 Answers1

7

Yes, it is legal, because a char can be initialized from a char16_t. However, the result of the conversion is implementation-defined if the char is signed and the value is too large to fit (C++11 §4.7/3). (Whether char is signed or unsigned is also implementation-defined, §3.9.1/1.)

As pointed out in comments, this will not convert your string into another encoding. (That being said, it will probably work in the case that the string contains only ASCII characters. That being said, don't do it.)

Brian Bi
  • 111,498
  • 10
  • 176
  • 312