简体   繁体   中英

What is <<= operator in C++

I found following code in a legacy system.As it seems to be a "assign and left shift" but I see this code is copying a string to ws but I couldn't understand how ? I wonder if simple assignment would have been enough to copy one string to another then why someone would code like this ?

vector<string> unique_dirs; 
......
......
......

std::wstring ws;
ws <<= unique_dirs[i];

Edit - I looked at the class implementation (c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\include\\xstring) . There is no such operator "<<=" overloaded in the class.

There is no such standard overload operator the left operand of which is std::wstring and the right operand is std::string. You should investigate the code where this operator was encountered that to find its definition.

By default :

ws <<= unique_dirs[i]

is the same as :

ws = ws << unique_dirs[i]

It is simply the Bitwise left shift assignment. But in this case, it should be overloaded to work with strings.

Despite my comment that investigating the code would be easier than people guessing what is happening, here is my guess at a possible implementation, as you were wondering how it could be done - this could appear anywhere in the code, pretty much, providing it can be seen where it is being called, as it's not modifying any of the standard library classes:

std::wstring& operator<<=(std::wstring& out, const std::string& in) {
    out += std::wstring(in.begin(), in.end());
    return out;
}

My guess here is that as a string is being passed to a wstring , the operator is performing some kind of "widening" (a poor-mans conversion from char to wchar , disregarding encoding).

Why would you want this rather than using a straight assignment? Well, aside from ws = unique_dirs[i]; being a compilation error, it could provide you with a method of concatenating strings:

std::string hello("hello ");
std::string goodbye("goodbye");
std::wstring ws;

ws <<= hello;
ws <<= goodbye;
// ws now is L"hello goodbye"

As an aside, the above does not modify the standard library - it is not extending the std::basic_string class, it's simply providing an operator that takes two classes as parameters. So I'm not sure how it comes under "legality" with regards its usage. It is fairly horrific, however, and its usage is morally reprehensible.

Unless the <<= is overloaded, It is the bitwise left shift operator.

ws <<= unique_dirs[i] means ws = ws << unique_dirs[i]

Although I am doubtful about the logic behind how the code is using some string element in the vector for this purpose.

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