Implementing the copy constructor in terms of operator=

后端 未结 8 1923
自闭症患者
自闭症患者 2020-12-28 16:19

If the operator= is properly defined, is it OK to use the following as copy constructor?

MyClass::MyClass(MyClass const &_copy)
{
    *this          


        
8条回答
  •  温柔的废话
    2020-12-28 16:44

    It is technically OK, if you have a working assignment operator (copy operator).

    However, you should prefer copy-and-swap because:

    • Exception safety is easier with copy-swap
    • Most logical separation of concerns:
      • The copy-ctor is about allocating the resources it needs (to copy the other stuff).
      • The swap function is (mostly) only about exchanging internal "handles" and doesn't need to do resource (de)allocation
      • The destructor is about resource deallocation
      • Copy-and-swap naturally combines these three function in the assignment/copy operator

提交回复
热议问题