In C++, placement new and copy constructor implementing copy assignment operator, is it a good practice?

Viewed 98

Given the code

struct Foo{
  Foo(const Foo &other){
    i = other.i;
  };

  Foo &operator=(const Foo &other){
    if(this == &other){
      return (*this);
    }

    new (this) Foo(other);
    return (*this);
  };
  
  int i = 0;
};


struct Bar{
  Bar &operator=(const Bar &other){
    if(this == &other){
      return (*this);
    }

    this->i = other.i;
    return (*this);
  };

  Bar(const Bar &other){
    (*this) = other;
  };
  
  int i = 0;
}

Assuming everything in the class is copyable, is it a good practice to avoid some repeated codes(consider classes with a lot of members) in the two forms above(class Foo and Bar), any potential danger? If so, which one is better?

0 Answers
Related