简体   繁体   中英

Garbage value in implicit conversion from expression `wchar_t + wchar_t[]` to std::wstring

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 literal L"B" with the promoted value of firstChar . It doesn't concatenate the character and the string. This is undefined behavior since std::basic_string will try to copy the string until it finds L'\\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM