본문 바로가기
Study/개발 지식

[개발 지식][C++/C#] 얕은 복사, 깊은 복사

by 스테디코디스트 2023. 10. 31.
반응형

1. 얕은 복사(shallow copy)

- 한 객체의 모든 멤버 변수의 값을 다른 객체로 복사

- 실제 포인터가 가리키는 값은 같기 때문에 한 쪽이 변하면 다른 한 쪽도 따라서 변함

 

2. 깊은 복사(deep copy)

- 한 객체의 모든 멤버 변수의 값 뿐만 아니라, 포인터 변수가 가리키는 모든 객체에 대해서도 복사

- 포인터까지 복사가 되어 생기는 것으로, 한 쪽이 아무리 바뀌어도 다른 한 쪽에는 영향이 없음

 

3. 소스코드(C++)

// c++
#include <iostream>
#include <vector>
#include <string>

#define _CRT_SECURE_NO_WARNINGS

using namespace std;

class Student
{
public:
	char* name;
	int age;

	Student(const char* _name, int _age)
	{
		name = new char[strlen(_name) + 1];
		strcpy(name, _name);

		age = _age;
	}
	
	Student DeepCopy()
	{
		Student s("A", 10);
				
		s.name = new char[strlen(s.name) + 1];
		age = s.age;
		
		return s;
	}
};

int main()
{
	Student s1("Lee", 26);
	Student s2(s1);

	strcpy(s2.name, "Park");
	
	cout << "얕은 복사" << endl;
	cout << s1.name << " " << s1.age << endl;
	cout << s2.name << " " << s2.age << endl;

	cout << "-------------------------------------" << endl;

	Student s3 = Student("Kim", 26);
	Student s4 = s3.DeepCopy();

	strcpy(s4.name, "Choi");

	cout << "깊은 복사" << endl;
	cout << s3.name << " " << s3.age << endl;
	cout << s4.name << " " << s4.age << endl;
}

cf) strcpy 오류가 뜨는 경우

- 프로젝트>프로젝트 속성>C/C++> 전처리기>전처리기 정의>편집>_CRT_SECURE_NO_WARNINGS 추가>적용

 

 

4. 소스코드(C#)

// c#
using System;

namespace StudyCSharp
{
    class Monster
    {
        public int hp;
        public int damage;

        public Monster(int hp, int damage)
        {
            this.hp = hp;
            this.damage = damage;
        }

        public Monster DeepCopy()
        {
            Monster newMonster = new Monster(0, 0);
            newMonster.hp = this.hp;
            newMonster.damage = this.damage;

            return newMonster;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 얕은 복사
            Monster Monster1 = new Monster(100, 5);            

            Monster shallowMonster = Monster1;
            shallowMonster.hp = 200;

            Console.WriteLine("얕은 복사");
            Console.WriteLine($"myMonster HP : {Monster1.hp}");
            Console.WriteLine($"otherMonster HP : {shallowMonster.hp}");


            Console.WriteLine("-----------------------------------------------");

            // 깊은 복사
            Monster Monster2 = new Monster(100, 5);

            Monster deepMonster = Monster2.DeepCopy();
            deepMonster.hp = 200;

            Console.WriteLine("깊은 복사");
            Console.WriteLine($"myMonster HP : {Monster2.hp}");
            Console.WriteLine($"deepMonster HP : {deepMonster.hp}");
        }        
    }    
    
}