C ++: The concept of shallow copy and deep copy

First of all, let's see if there is a problem with the implementation of the following string class?

class String
{
	char* _str;
public:
    String(const char* str = "")
    {
		// 构造string类对象时,如果传递nullptr指针,认为程序非法,此处断言下 
		if(nullptr == str)
		{
            assert(false);
			return; 
		}
        _str = new char[strlen(str) + 1];
        strcpy(_str, str);
    }
	~String() {
		if(_str) {
        	delete[] _str;
			_str = nullptr;
    	}
	}
};

// 测试
void TestString() {
    String s1("hello bit!!!");
    String s2(s1);
}

Insert picture description here

The above String class does not explicitly define its copy constructor and assignment operator overloading. At this time, the compiler will synthesize the default. When s1 is used to construct s2, the compiler will call the default copy construction. The problem eventually caused is that s1 and s2 share the same memory space, and the same block of space is released multiple times during release, causing the program to crash . This copy method is called shallow copy.

Shallow copy

Shallow copy: Also called bit copy, the compiler just copies the value in the object. If resources are managed in an object, multiple objects will eventually share the same resource. When an object is destroyed, the resource will be released. At this time, other objects do not know that the resource has been released and think it is still valid, so When you continue to operate on resources, an access violation will occur . To solve the shallow copy problem, deep copy was introduced in C ++.

Deep copy

If resource management is involved in a class, its copy constructor, assignment operator overloading, and destructor must be given explicitly. Generally, it is provided in the form of deep copy.

Insert picture description here

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105060174