An example: 0. Copy constructor

  1. Default constructor
  2. Normal constructor
  3. A FUNCTION PROTOTYPE
  4. Copy constructor
  5. Default constructor
  6. Copy constructor
    • Copy constructor
    • Copy assignment
    • Copy constructor(For return!)

Copy Operation

When we did not define our own copy constructor, cpp will generate one for us which just simply copy every single value.

So, what a copy constructor or assignment needs to do?

  • Copy constructor
  • Copy assignment Not a constructor, but a [[Operator Overloading|Overloading of =]]!

Prevent from Copying

When Own Special Member Function is Needed?

An Example

class MyClass {
public:
    int* ptr;
    MyClass() { ptr = new int(42); }
    MyClass(const MyClass& other) { // 拷贝构造
        ptr = new int(*other.ptr);
    }
    MyClass& operator=(const MyClass& other) { // 拷贝赋值
        if (this != &other) {
            delete ptr;
            ptr = new int(*other.ptr);
        }
        return *this;
    }
    ~MyClass() { delete ptr; }
};
 
MyClass f() {
    MyClass tmp;
    return tmp;
}
MyClass a;
a = f();

But something is optimized after c++17 which called Move Semantics.

Move Operation