Assignment operators

Assignment operators modify the value of the object.

# Declarations

T*& operator=(T*&, T*);
T*volatile & operator=(T*volatile &, T*);

# Example

#include <iostream>
 
int main()
{
    int n = 0;        // not an assignment
 
    n = 1;            // direct assignment
    std::cout << n << ' ';
 
    n = {};           // zero-initialization, then assignment
    std::cout << n << ' ';
 
    n = 'a';          // integral promotion, then assignment
    std::cout << n << ' ';
 
    n = {'b'};        // explicit cast, then assignment
    std::cout << n << ' ';
 
    n = 1.0;          // floating-point conversion, then assignment
    std::cout << n << ' ';
 
//  n = {1.0};        // compiler error (narrowing conversion)
 
    int& r = n;       // not an assignment
    r = 2;            // assignment through reference
    std::cout << n << ' ';
 
    int* p;
    p = &n;           // direct assignment
    p = nullptr;      // null-pointer conversion, then assignment
    std::cout << p << ' ';
 
    struct { int a; std::string s; } obj;
    obj = {1, "abc"}; // assignment from a braced-init-list
    std::cout << obj.a << ':' << obj.s << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
CWG 1527C++11for assignments to class type objects, the right operandcould be an initializer list only when the assignmentis defined by a user-defined assignment operatorremoved user-definedassignment constraint
CWG 1538C++11E1 = {E2} was equivalent to E1 = T(E2)(T is the type of E1), this introduced a C-style castit is equivalentto E1 = T{E2}
CWG 2654C++20compound assignment operators for volatile-qualified types were inconsistently deprecatednone of themis deprecated
CWG 2768C++11an assignment from a non-expression initializer clauseto a scalar value would perform direct-list-initializationperforms copy-list-initialization instead
CWG 2901C++98the value assigned to an unsigned intobject through an int lvalue is unclearmade clear
P2327R1C++20bitwise compound assignment operators for volatile typeswere deprecated while being useful for some platformsthey are notdeprecated

# See also