반응형
안녕하세요. 훈츠입니다. 금일은 클래스 객체 복사에 관련 포스팅 합니다.
클래스 객체 복사의 문제점
생성자에 메모리 할당이 있는 경우는 프로그램이 다운되며, 복사와 동시에 클래스를 초기화 하는 경우 생성자가 호출되지 않습니다.
-
메모리를 생성하는 생성자를 사용하는 경우 클래스 객체의 복사는 해제할 메모리 주소를 잃어버리게 하여 프로그램을 다운되게 합니다.
-
클래스를 복사함과 동시에 초기화 하는것은 생성자가 호출되지 않는 단점이 있다.
객체 복사시, 생성자 호출 되지 않는 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
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
|
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
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 |
'컴퓨터 언어 > C++' 카테고리의 다른 글
[C++] C++ 19일차 static(정적) 클래스와 지역 정적(static)클래스 1강 (0) | 2020.04.23 |
---|---|
[C++] C++ 18일차 오버로딩 4 (복사 생성자) (0) | 2020.04.22 |
[C++] C++ 16일차 함수 오버로딩 2 (0) | 2020.04.20 |
[C++] C++ 15일차 연산자 오버로딩 (0) | 2020.04.17 |
[C++] C++ 14일차 가상함수와 추상클래스 (0) | 2020.04.16 |