Copy constructor and assignment operator

Do you need to copy constructors in a class?
Sometimes the answer is "yes." if your class has resources assigned to it in the constructor, you may need an explicit copy constructor to manage the resources.
Classes with destructors usually use destructors to release resources allocated by constructors, which also indicates that a copy constructor is needed.
If you need to copy a constructor, you probably need an assignment operator. The assignment of class X is defined by X:operator =. Generally, X:operator should return an X &, and end with return *this to ensure the consistency with the built-in assignment operator.

Myclass obj1;
MyClass obj2 = obp1; / / when creating obp2, initialize it with the value of obp1 and use the copy constructor. If it cannot be found, it will create one by itself.
Myclass(const Myclass &rhs)

With destructor - with copy constructor - with copy constructor - with assignment operator


#include <iostream>
#include <string>

class MyClass
    MyClass(int *p);
    MyClass(const MyClass &rhs);

    MyClass &operator=(const MyClass &rhs);
    void print();
    int *ptr;

MyClass::MyClass(int *p)
    std::cout << "Enter main constructor\n";
    ptr = p;
    std::cout << "Leaving the main constructor\n";

MyClass::MyClass(const MyClass &rhs)
    std::cout << "Enter replica constructor\n";
    *this = rhs;
    std::cout << "Leave replica constructor\n";

    std::cout << "Enter the destructor\n";
    delete ptr;
    std::cout << "Disentangler\n";

MyClass &MyClass::operator=(const MyClass &rhs)
    std::cout << "Enter assignment statement overload\n";
    if( this != &rhs )
        delete ptr;

        ptr = new int;
        *ptr = *rhs.ptr;
        std::cout << "Both sides of the assignment number are the same object, no processing!\n"; // obj1 = obj1;

    std::cout << "Leave assignment statement overload\n";

    return *this;

void MyClass::print()
    std::cout << *ptr << std::endl;

int main()
    MyClass obj1(new int(1));
    MyClass obj2(new int(2));
    obj2 = obj1;

    std::cout << "-------------------------------\n";

    MyClass obj3(new int(3));
    MyClass obj4 = obj3;

    std::cout << "-------------------------------\n";

    MyClass obj5(new int(5));
    obj5 = obj5;

    return 0;

Posted on Fri, 27 Mar 2020 08:29:32 -0700 by alexville