nakka soft world !

C++ Explicit Casting 본문

프로그래밍언어/C++

C++ Explicit Casting

nakka 2017. 3. 15. 17:24
728x90

C++ Explicit Casting


int main()

{

int n = 10; // 4바이트 메모리


double* p1 = &n; // error

double* p1 = (double*)&n; // ok


*p1 = 3.4;  // OK이더라도 운이 좋으면 Crash. 운나쁘면 메모리 침범

}



int main()

{

const int c = 10; // 상수


int* p2 = &c; // error

int* p2 = (int*)&c; // ok


*p2 = 20;


cout << c << endl; // 10? or 20?. 

cout << *p << endl; // 10? or 20?. 

}


결과적으로 C에서 제공하는 Casting은 매우 위험하다.



int main()

{

// void* => int* 캐스팅 필요

int* p = (int*)malloc(sizeof(int)*10); // C스타일

int* p = static_cast<int*>( malloc(sizeof(int)*10) ); // C++. OK.

free(p);



int n = 10; // 4바이트 메모리

double* p1 = static_cast<double*>&n; // error. 컴파일러 판단상 위험한 부분이라 Compiler Error.

double* p1 = reinterpret_cast<double*>&n; // error. 사용자가 무조건 Casting 하겠다하면 이와 같이 사용. 대부분 성공.


*p1 = 3.4;

}



int main()

{

const int c = 10; // 상수


//int* p2 = (int*)&c; // ok

int* p2 = static_cast<int*>(&c); // error

int* p2 = reinterpret_cast<int*>(&c); // 변수의 상수성 때문에 casting error 발생


int* p2 = const_cast<int*>(&c); // ok. 상수성을 제거하는 캐스팅.

*p2 = 20; // 가능하나 상수성을 잃어 버렸기에 혼란스러움.

}



728x90

'프로그래밍언어 > C++' 카테고리의 다른 글

making stack  (0) 2017.03.16
OOP Concept  (0) 2017.03.16
reference  (0) 2017.03.15
namespace  (0) 2017.03.15
동적 메모리 할당  (0) 2017.03.14
Comments