C++_ detailed explanation of deep and shallow copy

1. Shallow copy

1.1 Shallow copy concept

  • Also known as 值拷贝copying the value of the source object to the target copy object, in essence, the source object and the target copy object 共用一份实体, but the referenced variable name is different, the address is actually the same.
    Example: Similar to the reference in C++, use different names to point to the same block of address.

1.2 Shallow copy icon

Insert picture description here

1.3 Shallow copy code example

1.3.1 Without destructor

#include<iostream>
#include<string>
#pragma warning(disable:4996)

using namespace std;

namespace mystring
{
    
    
	class string
	{
    
    
	public:
		string(const char* str = "")
			:_str(new char[strlen(str)+1])
		{
    
    
			strcpy(_str, str);
		}
		string& operator=(const string& s)
		{
    
    
			_str = s._str;
		}
		char& operator[](int i)
		{
    
    
			return _str[i];
		}

		const char* c_str()
		{
    
    
			return _str;
		}

	private:
		char* _str;
	};
}

int main()
{
    
    
	mystring::string str1("Hello World!\n");
	mystring::string str2 = str1;
	str2[0] = 'h';
	cout << str1.c_str()<< endl;
	cout << str2.c_str() << endl;
}

operation result:
Insert picture description here

Analysis result:

  1. First, the content in the object str1 is constructed "Hello World!".

  2. Then 浅拷贝copy the content of str1 to str2 in the same way
    str2 = str1;.

  3. At this time, it can be seen from the output result that the contents of str1 and str2 are the same as " Hello World!"

  4. When changed str2[0]的字符为‘h’, both str1 and str2 are output at the same time hello world!.

1.3.2 Added destructor

Part of the code, the rest of the code is the same as above without destructor.


		const char* c_str()
		{
    
    
			return _str;
		}

		~string()
		{
    
    
			delete[] _str;
		}

	private:
		char* _str;
	};
}

Operation result:
Insert picture description here
analysis result:

  1. After adding the destructor, run an error.
    Reason: str1 called the destructor first, and the same address was destructed by str1 when str2 called the destructor. This is also the case 浅拷贝常见的问题.

1.4 Summary of Shallow Copy

  1. Once str2 is operated, the content of str1 will also change;
  2. When destructuring, str1 is first deconstructed, and then str2 is deconstructed. However, since str1 and str2 point to the same space, the secondary destruction of a space will lead to errors.

解决出错问题便引入了深拷贝。

2 Deep copy

2.1 Deep copy concept

  • Pass the 开辟和原空间大小相同的空间并将内容拷贝operation again. Regardless of whether str1 is operated or not, a piece of space and content of the same size will be copied.

2.2 Deep copy icon

Insert picture description here

2.3 Deep copy code example

#include<iostream>
#include<string>
#pragma warning(disable:4996)

using namespace std;

namespace mystring
{
    
    
	class string
	{
    
    
	public:
		string(const char* str = "")
			:_str(new char[strlen(str)+1])
		{
    
    
			strcpy(_str, str);
		}
		//现代写法
		string(const string& s)
			:_str(NULL)//为了交换以后tmp为NULL析构NULL。
		{
    
    
			string tmp(s._str);   
			swap(_str, tmp._str);  
		}
		//现代写法
		string& operator=(const string& s)
		{
    
    
			if (this != &s)
			{
    
    
				string tmp(s._str);    
				swap(_str, tmp._str);  
			}
			return *this;
		}
		
		char& operator[](int i)
		{
    
    
			return _str[i];
		}

		const char* c_str()
		{
    
    
			return _str;
		}

		~string()
		{
    
    
			delete[] _str;
		}

	private:
		char* _str;
	};
}

int main()
{
    
    
	mystring::string str1("Hello World!\n");
	mystring::string str2 = str1;
	cout << str1.c_str() << endl;
	cout << str2.c_str() << endl;
	str2[0] = 'h';
	cout << str1.c_str()<< endl;
	cout << str2.c_str() << endl;
}

Operation result:
Insert picture description here
analysis result:

  1. First, the content in the object str1 is constructed "Hello World!".

  2. Then 浅拷贝copy the content of str1 to str2 in the same way
    str2 = str1;.

  3. At this time, it can be seen from the output result that the contents of str1 and str2 are the same as " Hello World!"

  4. When the change is made str2[0]的字符为‘h’, str1 is output at the same time or " Hello world!", str2 becomes hello World!.

  5. When destructing, str1 is first deconstructed, and then str2 is deconstructed, but since str1 and str2 point to different spaces, it will not report an error like a shallow copy.

2.4 Deep copy summary

  1. Since the space is reopened for str2 and the content of str1 is copied to the newly opened space of str2, str2 has a new address space, so changing the content of str2 will not affect str1.
  2. Even if the destructor function is added, str1 is destructed first, and then str2 is destructed. However, since str1 and str2 point to different spaces, it will not report an error like a shallow copy.

Guess you like

Origin blog.csdn.net/weixin_45313447/article/details/115299372