Home > Mobile >  why doesn't assignment of int to std::map<string,string> produce a compiler error
why doesn't assignment of int to std::map<string,string> produce a compiler error

Time:12-28

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.

  • Related