본문 바로가기
Language/C++

[c++] 깊은 복사(Deep copy)와 얕은 복사(shallow copy)

by 담백로봇 2022. 11. 23.

코딩을 공부하다보면 자꾸 깊은 복사와 얕은 복사에 대한 개념이 나오는데 무슨 개념인가 너무 궁금해 정리.

 

한줄로 정리하면

=> 얕은 복사는 reference를 이용해 한 공간의 메모리를 공유하는 형태로 사용하는것.

=> 깊은 복사는 각각의 오브젝트가 각각의 메모리를 가지고있는것.

얖은 , 깊은 복사 memory view

<참고 자료 > geeksforgeeks

 


얕은 복사 예제! (너무 잘 표현하고있어서 통쨰로 )

// C++ program for the above approach
#include <iostream>
using namespace std;

// Box Class
class box {
private:
	int length;
	int breadth;
	int height;

public:
	// Function that sets the dimensions
	void set_dimensions(int length1, int breadth1,
						int height1)
	{
		length = length1;
		breadth = breadth1;
		height = height1;
	}

	// Function to display the dimensions
	// of the Box object
	void show_data()
	{
		cout << " Length = " << length
			<< "\n Breadth = " << breadth
			<< "\n Height = " << height
			<< endl;
	}
};

// Driver Code
int main()
{
	// Object of class Box
	box B1, B3;

	// Set dimensions of Box B1
	B1.set_dimensions(14, 12, 16);
	B1.show_data();

	// When copying the data of object
	// at the time of initialization
	// then copy is made through
	// COPY CONSTRUCTOR 는 얕은복사라는 얘기지!
	box B2 = B1;
	B2.show_data();

	// When copying the data of object
	// after initialization then the
	// copy is done through DEFAULT
	// ASSIGNMENT OPERATOR  이렇게도 해도 같은 결과!
	B3 = B1;
	B3.show_data();

	return 0;
}

Output:

Length = 14
 Breadth = 12
 Height = 16
 Length = 14
 Breadth = 12
 Height = 16
 Length = 14
 Breadth = 12
 Height = 16

깊은복사 예제

 

// C++ program to implement the
// deep copy
#include <iostream>
using namespace std;

// Box Class
class box {
private:
	int length;
	int* breadth;
	int height;

public:
	// Constructor
	box()
	{
		breadth = new int;
	}

	// Function to set the dimensions
	// of the Box
	void set_dimension(int len, int brea,
					int heig)
	{
		length = len;
		*breadth = brea;
		height = heig;
	}

	// Function to show the dimensions
	// of the Box
	void show_data()
	{
		cout << " Length = " << length
			<< "\n Breadth = " << *breadth
			<< "\n Height = " << height
			<< endl;
	}

	// Parameterized Constructors for
	// for implementing deep copy
	box(box& sample)
	{
		length = sample.length;
		breadth = new int;
		*breadth = *(sample.breadth);
		height = sample.height;
	}

	// Destructors
	~box()
	{
		delete breadth;
	}
};

// Driver Code
int main()
{
	// Object of class first
	box first;

	// Set the dimensions
	first.set_dimension(12, 14, 16);

	// Display the dimensions
	first.show_data();

	// When the data will be copied then
	// all the resources will also get
	// allocated to the new object
	box second = first;

	// Display the dimensions
	second.show_data();

	return 0;
}

여기서 new 가 들어가면서 깊은복사를해줘야 first 오브젝트가 second에 복사됨을 알 수있다. 만약 breath 를 box(box& a) 에서 처리해준것처럼 처리해주지않으면 복사가 안됨..

댓글