This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of NAD status.

2372. Assignment from int to std::string

Section: 24.3.2 [basic.string] Status: NAD Submitter: Andrzej Krzemieński Opened: 2014-03-13 Last modified: 2017-02-03

Priority: 4

View other active issues in [basic.string].

View all other issues in [basic.string].

View all issues with NAD status.


The following code works in C++:

int i = 300;
std::string threeHundred;
threeHundred = i;

"Works" == "Compiles and doesn't have an undefined behavior". But it may not be obvious and in fact misleading what it does. This assignment converts an int to char and then uses string's assignment from char. While the assignment from char can be considered a feature, being able to assign from an int looks like a safety gap. Someone may believe C++ works like "dynamically typed" languages and expect a lexical conversion to take place.

Ideally the assignment from char could be deprecated and later removed, but as a less intrusive alternative one could consider adding a SFINAEd deleted function template:

template <typename IntT> // enable if is_integral<IntT>::value
basic_string& operator=(IntT) = delete;

[Lenexa 2015-06-06: Move to LEWG]

RS: std::string x('0' + n); broken by this.

MC: This is an extension, move to LEWG.

Move to LEWG, consensus.

Previous resolution [SUPERSEDED]:

This wording is relative to N3936.

  1. To 24.3.2 [basic.string], class template basic_string synopsis, add as indicated:

    basic_string& operator=(const basic_string& str);
    basic_string& operator=(basic_string&& str) noexcept;
    basic_string& operator=(const charT* s);
    basic_string& operator=(charT c);
    template <class IntT> basic_string& operator=(IntT i) = delete;
    basic_string& operator=(initializer_list<charT>);
  2. Add after [string.cons] p26 as indicated:

    basic_string& operator=(charT c);

    -26- Returns: *this = basic_string(1,c).

    template <class IntT> basic_string& operator=(IntT i) = delete;

    -?- Remarks: This signature shall not participate in overload resolution unless is_integral<T>::value is true.

[2016-03, Jacksonville]


This needs a paper; close the issue

We don't think the breakage is acceptable.

Guidance to author: Look for a way to encourage a warning; discomfort with calling that "deprecation".

Consider += and push_back.

Proposed resolution:

This should be addressed by a paper addressed to LEWG.