I have come across something weird in Visual Studio C++ 2013 Community Edition which is either a compiler bug or I'm writing invalid code that does compile without warnings.
Consider the following snippet:
#include <string>
#include <iostream>
int main()
{
std::wstring text;
wchar_t firstChar = 'A';
text = firstChar + L"B";
std::wcout << text << std::endl;
return 0;
}
I expect the output to be "AB" but what I get is random garbage.
My question: is the operator+
between the wchar_t
and wchar_t[]
ill-defined, or is this a compiler/library bug?
In the case that it is ill-defined, should the compiler have issued a warning?
Note: I am not looking for a solution/workaround. Changing L"B"
to std::wstring(L"B")
fixes the problem. What I want to know is if I did something wrong or if the compiler did.
Note 2: I also get a garbage result in Visual Studio C++ 2010 and an online compiler which supposedly uses g++, and no compilation error, so I'm leaning towards that code being invalid, even though I would expect a compiler error.
firstChar + L"B"
increments the address of the string literalL"B"
with the promoted value offirstChar
. It doesn't concatenate the character and the string. This is undefined behavior sincestd::basic_string
will try to copy the string until it findsL'\0'
, which is beyond its original bound.std::basic_string
has multiple overloaded operators that allow operations like this to have intuitive behavior, which is why it works in that case.