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?
CodePudding user response:
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
.