Assignment operator - Self-assignment

前端 未结 3 1012
梦如初夏
梦如初夏 2021-01-08 01:25

Does the compiler generated assignment operator guard against self assignment?

class T {

   int x;
public:
   T(int X = 0): x(X) {}
};

int main()
{
   T a(         


        
相关标签:
3条回答
  • 2021-01-08 01:30
    class T {
        int x;
    public:
        T(int X = 0): x(X) {}
    // prevent copying
    private:
        T& operator=(const T&);
    };
    
    0 讨论(0)
  • 2021-01-08 01:40

    Does the compiler generated assignment operator guard against self assignment?

    No, it does not. It merely performs a member-wise copy, where each member is copied by its own assignment operator (which may also be programmer-declared or compiler-generated).

    Do I always need to protect against self-assignment even when the class members aren't of pointer type?

    No, you do not if all of your class's attributes (and therefore theirs) are POD-types.

    When writing your own assignment operators you may wish to check for self-assignment if you want to future-proof your class, even if they don't contain any pointers, et cetera. Also consider the copy-and-swap idiom.

    0 讨论(0)
  • 2021-01-08 01:47

    This is an easy one to check empirically:

    #include <iostream>
    struct A {
      void operator=(const A& rhs) {
        if(this==&rhs) std::cout << "Self-assigned\n";
      }
    };
    
    struct B {
      A a;
    };
    
    int main()
    {
      B b;
      b = b;
    }
    
    0 讨论(0)
提交回复
热议问题