1

Attempting to assign an int to a string std::string s = 5; produces the following compiler error:

error: conversion from ‘int’ to non-scalar type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} requested

however assigning an int to the value of a string in a map doesn't. For example the below code compiles, and worse yet makes the assignment converting the int to a char

map <string, string>m;
m["test"] = 5;

Shouldn't this be an error?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
user438431
  • 335
  • 4
  • 15

1 Answers1

5

This shouldn't be an error. m["test"] = 5; performs assignment, and std::string has an assignment operator taking char, and int could be converted to char implicitly.

constexpr basic_string& operator=( CharT ch );

On the other hand, std::string s = 5; is not assignment but initialization; and std::string doesn't have any constructors taking int or char.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • oh geez, I completely overlooked that it was the constructor. however int x=9000, s = x, produces some wild results, so it seems to me that assignment from int and not char is kind of risky, but of course that's a different question – user438431 Dec 27 '21 at 03:22
  • @user438431 - That specific assignment operator from char to string is a bit odd, and kind of a mistake in the API. It has been briefly considered to remove it, but backward compatibility, and all that... – BoP Dec 27 '21 at 09:41