public member function
<string>

std::string::operator=

string (1)
string& operator= (const string& str);
c-string (2)
string& operator= (const char* s);
character (3)
string& operator= (char c);
string (1)
string& operator= (const string& str);
c-string (2)
string& operator= (const char* s);
character (3)
string& operator= (char c);
initializer list (4)
string& operator= (initializer_list<char> il);
move (5)
string& operator= (string&& str) noexcept;
String assignment
Assigns a new value to the string, replacing its current contents.

(See member function assign for additional assignment options).

Parameters

str
A string object, whose value is either copied (1) or moved (5) if different from *this (if moved, str is left in an unspecified but valid state).
s
Pointer to a null-terminated sequence of characters.
The sequence is copied as the new value for the string.
c
A character.
The string value is set to a single copy of this character (the string length becomes 1).
il
An initializer_list object.
These objects are automatically constructed from initializer list declarators.
The characters are copied, in the same order.

Return Value

*this

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// string assigning
#include <iostream>
#include <string>

int main ()
{
  std::string str1, str2, str3;
  str1 = "Test string: ";   // c-string
  str2 = 'x';               // single character
  str3 = str1 + str2;       // string

  std::cout << str3  << '\n';
  return 0;
}

Output:
Test string: x


Complexity

Unspecified.
Unspecified, but generally linear in the new string length (and constant for the move version).

Iterator validity

Any iterators, pointers and references related to this object may be invalidated.

Data races

The object is modified.
The move assignment (5) modifies str.

Exception safety

For the move assignment (5), the function does not throw exceptions (no-throw guarantee).
In all other cases, there are no effects in case an exception is thrown (strong guarantee).

If the resulting string length would exceed the max_size, a length_error exception is thrown.
A bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also