Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      Assignment operators

      From cppreference.com
      <cpp‎ |language
       
       
      C++ language
      General topics
      Flow control
      Conditional execution statements
      Iteration statements (loops)
      Jump statements
      Functions
      Function declaration
      Lambda function expression
      inline specifier
      Dynamic exception specifications(until C++17*)
      noexcept specifier(C++11)
      Exceptions
      Namespaces
      Types
      Specifiers
      constexpr(C++11)
      consteval(C++20)
      constinit(C++20)
      Storage duration specifiers
      Initialization
      Expressions
      Alternative representations
      Literals
      Boolean -Integer -Floating-point
      Character -String -nullptr(C++11)
      User-defined(C++11)
      Utilities
      Attributes(C++11)
      Types
      typedef declaration
      Type alias declaration(C++11)
      Casts
      Memory allocation
      Classes
      Class-specific function properties
      Special member functions
      Templates
      Miscellaneous
       
      Expressions
      General
      Literals
      Operators
      Conversions
       

      Assignment operators modify the value of the object.

      Operator name Syntax Over​load​ablePrototype examples (forclass T)
      Inside class definitionOutside class definition
      simple assignmenta = bYesT& T::operator=(const T2& b);N/A
      addition assignmenta += bYesT& T::operator+=(const T2& b);T& operator+=(T& a,const T2& b);
      subtraction assignmenta -= bYesT& T::operator-=(const T2& b);T& operator-=(T& a,const T2& b);
      multiplication assignmenta *= bYesT& T::operator*=(const T2& b);T& operator*=(T& a,const T2& b);
      division assignmenta /= bYesT& T::operator/=(const T2& b);T& operator/=(T& a,const T2& b);
      remainder assignmenta %= bYesT& T::operator%=(const T2& b);T& operator%=(T& a,const T2& b);
      bitwise AND assignmenta &= bYesT& T::operator&=(const T2& b);T& operator&=(T& a,const T2& b);
      bitwise OR assignmenta |= bYesT& T::operator|=(const T2& b);T& operator|=(T& a,const T2& b);
      bitwise XOR assignmenta ^= bYesT& T::operator^=(const T2& b);T& operator^=(T& a,const T2& b);
      bitwise left shift assignmenta <<= bYesT& T::operator<<=(const T2& b);T& operator<<=(T& a,const T2& b);
      bitwise right shift assignmenta >>= bYesT& T::operator>>=(const T2& b);T& operator>>=(T& a,const T2& b);
      Notes
      • All built-in assignment operators return*this, and mostuser-defined overloads also return*this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (includingvoid).
      • T2 can be any type includingT.

      Contents

      [edit]Definitions

      Copy assignment replaces the contents of the objecta with a copy of the contents ofb (b is not modified). For class types, this is performed in a special member function, described incopy assignment operator.

      Move assignment replaces the contents of the objecta with the contents ofb, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described inmove assignment operator.

      (since C++11)

      For non-class types, copy and move assignment are indistinguishable and are referred to asdirect assignment.

      Compound assignment replace the contents of the objecta with the result of a binary operation between the previous value ofa and the value ofb.

      [edit]Assignment operator syntax

      The assignment expressions have the form

      target-expr=new-value (1)
      target-expr op new-value (2)
      target-expr - the expression[1] to be assigned to
      op - one of*=,/=%=,+=-=,<<=,>>=,&=,^=,|=
      new-value - theexpression[2](until C++11)initializer clause(since C++11) to assign to the target
      1. target-expr must have higherprecedence than an assignment expression.
      2. new-value cannot be a comma expression, because itsprecedence is lower.
      1) Simple assignment expression.
      2) Compound assignment expression.

      Ifnew-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

      (since C++11)

      [edit]Built-in simple assignment operator

      For the built-in simple assignment,target-expr must be a modifiable lvalue.

      The object referred to bytarget-expr is modified by replacing its value with the result ofnew-value. If the object referred is of an integer typeT, and the result ofnew-value is of the corresponding signed/unsigned integer type, the value of the object is replaced with the value of typeT with the same value representation of the result ofnew-value.

      The result of a built-in simple assignment is an lvalue of the type oftarget-expr, referring totarget-expr. Iftarget-expr is abit-field, the result is also a bit-field.

      [edit]Assignment from an expression

      Ifnew-value is an expression, it isimplicitly converted tothe cv-unqualified type oftarget-expr. Whentarget-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

      Iftarget-expr andnew-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

      If the type oftarget-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is adiscarded-value expression or anunevaluated operand.

      (since C++20)


      Assignment from a non-expression initializer clause

      new-value is only allowed not to be an expression in following situations:

      • target-expr is of ascalar typeT, andnew-value is empty or has only one element. In this case, given an invented variablet declared and initialized asT t= new-value , the meaning ofx= new-value  isx= t.
      • target-expr is of class type. In this case,new-value is passed as the argument to the assignment operator function selected byoverload resolution.
      #include <complex> std::complex<double> z;z={1,2};// meaning z.operator=({1, 2})z+={1,2};// meaning z.operator+=({1, 2}) int a, b;a= b={1};// meaning a = b = 1;a={1}= b;// syntax error
      (since C++11)

      Inoverload resolution against user-defined operators, for every typeT, the following function signatures participate in overload resolution:

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

      For every enumeration or pointer to member typeT, optionally volatile-qualified, the following function signature participates in overload resolution:

      T& operator=(T&, T);

      For every pairA1 andA2, whereA1 is an arithmetic type (optionally volatile-qualified) andA2 is a promoted arithmetic type, the following function signature participates in overload resolution:

      A1& operator=(A1&, A2);

      [edit]Built-in compound assignment operator

      The behavior of every built-in compound-assignment expressiontarget-expr op = new-value is exactly the same as the behavior of the expressiontarget-expr = target-expr op new-value, except thattarget-expr is evaluated only once.

      The requirements ontarget-expr andnew-value of built-in simple assignment operators also apply. Furthermore:

      • For+= and-=, the type oftarget-expr must be anarithmetic type or a pointer to a (possibly cv-qualified) completely-definedobject type.
      • For all other compound assignment operators, the type oftarget-expr must be an arithmetic type.

      Inoverload resolution against user-defined operators, for every pairA1 andA2, whereA1 is an arithmetic type (optionally volatile-qualified) andA2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

      A1& operator*=(A1&, A2);
      A1& operator/=(A1&, A2);
      A1& operator+=(A1&, A2);
      A1& operator-=(A1&, A2);

      For every pairI1 andI2, whereI1 is an integral type (optionally volatile-qualified) andI2 is a promoted integral type, the following function signatures participate in overload resolution:

      I1& operator%=(I1&, I2);
      I1& operator<<=(I1&, I2);
      I1& operator>>=(I1&, I2);
      I1& operator&=(I1&, I2);
      I1& operator^=(I1&, I2);
      I1& operator|=(I1&, I2);

      For every optionally cv-qualified object typeT, the following function signatures participate in overload resolution:

      T*& operator+=(T*&,std::ptrdiff_t);
      T*& operator-=(T*&,std::ptrdiff_t);
      T*volatile& operator+=(T*volatile&,std::ptrdiff_t);
      T*volatile& operator-=(T*volatile&,std::ptrdiff_t);

      [edit]Example

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

      Possible output:

      1 0 97 98 1 2 (nil) 1:abc

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      CWG 1527C++11for assignments to class type objects, the right operand
      could be an initializer list only when the assignment
      is defined by a user-defined assignment operator
      removed user-defined
      assignment constraint
      CWG 1538C++11E1={E2} was equivalent toE1= T(E2)
      (T is the type ofE1), this introduced a C-style cast
      it is equivalent
      toE1= T{E2}
      CWG 2654C++20compound assignment operators for volatile
      -qualified types were inconsistently deprecated
      none of them
      is deprecated
      CWG 2768C++11an assignment from a non-expression initializer clause
      to a scalar value would perform direct-list-initialization
      performs copy-list-
      initialization instead
      CWG 2901C++98the value assigned to anunsignedint
      object through anint lvalue is unclear
      made clear
      P2327R1C++20bitwise compound assignment operators for volatile types
      were deprecated while being useful for some platforms
      they are not
      deprecated

      [edit]See also

      Operator precedence

      Operator overloading

      Common operators
      assignmentincrement
      decrement
      arithmeticlogicalcomparisonmember
      access
      other

      a= b
      a+= b
      a-= b
      a*= b
      a/= b
      a%= b
      a&= b
      a|= b
      a^= b
      a<<= b
      a>>= b

      ++a
      --a
      a++
      a--

      +a
      -a
      a+ b
      a- b
      a* b
      a/ b
      a% b
      ~a
      a& b
      a| b
      a^ b
      a<< b
      a>> b

      !a
      a&& b
      a|| b

      a== b
      a!= b
      a< b
      a> b
      a<= b
      a>= b
      a<=> b

      a[...]
      *a
      &a
      a->b
      a.b
      a->*b
      a.*b

      function call

      a(...)
      comma

      a, b
      conditional

      a? b: c
      Special operators

      static_cast converts one type to another related type
      dynamic_cast converts within inheritance hierarchies
      const_cast adds or removescv-qualifiers
      reinterpret_cast converts type to unrelated type
      C-style cast converts one type to another by a mix ofstatic_cast,const_cast, andreinterpret_cast
      new creates objects with dynamic storage duration
      delete destructs objects previously created by the new expression and releases obtained memory area
      sizeof queries the size of a type
      sizeof... queries the size of apack(since C++11)
      typeid queries the type information of a type
      noexcept checks if an expression can throw an exception(since C++11)
      alignof queries alignment requirements of a type(since C++11)

      C documentation forAssignment operators
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/language/operator_assignment&oldid=179770"

      [8]ページ先頭

      ©2009-2025 Movatter.jp