컴퓨터 언어/C++

[C++] C++ 17일차 오버로딩 3 (클래스 객체 복사시 주의사항)

훈츠 2020. 4. 21. 11:37
반응형

 

안녕하세요. 훈츠입니다. 금일은 클래스 객체 복사에 관련 포스팅 합니다.

 

클래스 객체 복사의 문제점

 

생성자에 메모리 할당이 있는 경우는 프로그램이 다운되며, 복사와 동시에 클래스를 초기화 하는 경우 생성자가 호출되지 않습니다.

 

  • 메모리를 생성하는 생성자를 사용하는 경우 클래스 객체의 복사는 해제할 메모리 주소를 잃어버리게 하여 프로그램을 다운되게 합니다. 

  • 클래스를 복사함과 동시에 초기화 하는것은 생성자가 호출되지 않는 단점이 있다.

 

객체 복사시, 생성자 호출 되지 않는 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class A
{
public:
    int m_nVar;
    A() { cout << "생성자 호출"<< endl ; }
    ~A() { cout << "소멸자 호출" << endl; }
    
};
 
int main()
{
    A test1;
    test1.m_nVar = 1;
    A test2 = test1;
    return 0;
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

strcpy_s 클래스 복사 코드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class A
{
public:
    char* m_pString;
    A(char *pStr) {
        m_pString = new char[strlen(pStr) + 1];
        strcpy_s(m_pString,sizeof(m_pString), pStr);
        cout << " 객체 주소 : "<<this <<"생성자 호출"<< endl ; 
    }
    ~A() {
        delete[] m_pString;
        cout << " 객체 주소 : " << this << "소멸자 호출" << endl;
    }
    void Print() {
        cout << m_pString <<" 주소값 : " <<this << endl;
    
    }
};
 
int main()
{
    char ss[] = "C++";
    char* pTemp = &ss[0];
    A test1(pTemp);
    
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

 

 

 

 

 

 

 

반응형