Reputation: 141
I found some very strange behavior of std::wstring.
#include "stdafx.h"
#include <string>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring someString = L"Some dummy string";
std::wstring base1 = L"Base1 ";
std::wstring base2 = L"Base2 ";
std::wstring second = L"Second";
base1 += second.at(0) + L" ";
base2 += second.at(0);
base2 += L" ";
return 0;
}
The base1 and base2 output should be the same, but there are not. Base1 is actually doesn't work.
Any ideas?
Upvotes: 1
Views: 160
Reputation: 103761
second.at(0) + L" "
This expression doesn't do what you expect. at(0)
returns a wchar_t
, which is really an integer. L" "
is a wide string literal, which is implicitly converted to a wchar_t const*
. So in the expression above, you are doing pointer arithmetic, adding whatever the value of L'S'
is (probably the same as the ASCII value of S
, which is 83, I believe). This gives you a pointer far outside the range of the string literal, which is only 2 characters. The end result is undefined behavior.
To get the effect you are probably going for, you can make one of your operands a wstring
.
base1 += second.at(0) + std::wstring(L" ");
Probably simpler in this case would be to just use 2 statements.
base1 += second.at(0);
base1 += L' ';
Upvotes: 8