简体   繁体   中英

Why `std::string`'s assignment operator take `char` by value and not `const` reference?

Accidentally I came across below situation:

int i = 1000;
string s;
s = i; // ok, but value of `s` is not 1000!

This situation was created due to below operator from string standard library:

string& string::operator=(_CharT __c) 
{ 
  this->assign(1, __c); 
  return *this;
}

Now, this is creating an unwanted bad effect where accidentally we may end up assigning an integer to a string with erroneous value!
For example, in my case i was earlier a string and then I converted to int . The code still compiled but the program crashed due to its obvious bad effect on overall code.

This situation would be avoided, if it was:

string& operator=(const _CharT& c);

What is the motivation behind not having above version?

What is the motivation behind not having above version?

It doesn't solve the problem (it doesn't work how you think it works) and it would be slower.

Passing a char (or even wchar_t or char32_t ) by value is faster on most architectures than creating a reference and then accessing through the reference, because it requires passing a pointer-sized object (which is usually bigger than a char and on 64-bit systems is probably also bigger than wchar_t ) and then doing an indirection through a pointer.

So it would not fix the problem you are trying to fix it would just make code slower. Double bad.

C++ allows int to char conversion, so your suggested overload would just create that temporary then bind a reference to it. See http://open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2372 for a better "fix", which has its own problems and is probably not going to happen.

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