std::basic_string<CharT,Traits,Allocator>::operator=

Replaces the contents of the string.

# Declarations

basic_string& operator=( const basic_string& str );

(constexpr since C++20)

basic_string& operator=( basic_string&& str )
noexcept(/* see below */);

(since C++11) (constexpr since C++20)

basic_string& operator=( const CharT* s );

(constexpr since C++20)

basic_string& operator=( CharT ch );

(constexpr since C++20)

basic_string& operator=( std::initializer_list<CharT> ilist );

(since C++11) (constexpr since C++20)

template<class StringViewLike>
basic_string& operator=( const StringViewLike& t );

(since C++17) (constexpr since C++20)

basic_string& operator=( std::nullptr_t ) = delete;

(since C++23)

# Parameters

# Return value

*this

# Example

#include <iomanip>
#include <iostream>
#include <string>
 
int main()
{
    std::string str1;
    std::string str2{"alpha"};
 
    // (1) operator=(const basic_string&);
    str1 = str2;
    std::cout << std::quoted(str1) << ' '   // "alpha"
              << std::quoted(str2) << '\n'; // "alpha"
 
    // (2) operator=(basic_string&&);
    str1 = std::move(str2);
    std::cout << std::quoted(str1) << ' '   // "alpha"
              << std::quoted(str2) << '\n'; // "" or "alpha" (unspecified)
 
    // (3) operator=(const CharT*);
    str1 = "beta";
    std::cout << std::quoted(str1) << '\n'; // "beta"
 
    // (4) operator=(CharT);
    str1 = '!'; 
    std::cout << std::quoted(str1) << '\n'; // "!"
 
    // (5) operator=(std::initializer_list<CharT>);
    str1 = {'g', 'a', 'm', 'm', 'a'};
    std::cout << std::quoted(str1) << '\n'; // "gamma"
 
    // (6) operator=(const T&);
    str1 = 35U; // equivalent to str1 = static_cast<char>(35U);
    std::cout << std::quoted(str1) << '\n'; // "#" (ASCII = 35)
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 847C++98there was no exception safety guaranteeadded strong exception safety guarantee
LWG 2063C++11the move assignment operator did not followSequenceContainer’s semantic requirementfollows
LWG 2946C++17overload (6) caused ambiguity in some casesavoided by making it a template

# See also