https://headerfile.tistory.com/64
volitile로 선언된 변수는 외부적인 요인으로 그 값이 언제든지 바뀔 수 있음을 뜻한다. 따라서 컴파일러는 volitile 선언된 변수에 대해서는 최적화를 수행하지 않는다. volitile 변수를 참조할 경우 레지스터에 로드된 값을 사용하지 않고 매번 메모리를 참조한다.
#include <iostream>
using namespace std;
// Returns a hash code based on an address
unsigned short Hash( void *p ) {
unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));
}
using namespace std;
int main() {
int a[20];
for ( int i = 0; i < 20; i++ )
cout << Hash( a + i ) << endl;
}
Output:
64641
64645
64889
64893
64881
64885
64873
64877
64865
64869
64857
64861
64849
64853
64841
64845
64833
64837
64825
64829
static_cast 는 포인터를 부모 클래스로 변환할때 사용할수있다.
하지만 안전하지 않다.
(dynamic_cast 로 하면 에러 날것이다.) 왜냐면 다운캐스팅을 막기 때문 다이나믹은
static_cast는 주로 숫자 데이터 형식을 변환 하는데 쓰인다.
열거형을 정수형으로 바꾸거나 정수형을 부동소수점형으로 바꾸는등 데이터의 변환이 확실히 가능한 곳에 쓸 수 있다.
static_cast는 런타임 검사를 하지 않으므로
dynamic_cast 보다 안전하지 않다.
dynamic_cast는 모호한 포인터는 실패한다. but
static_cast는 모호한 포인터도 이상없다 판단한다.
class A {virtual void f();};
class B : public A {virtual void f();};
class C : public A { };
class D {virtual void f();};
class E : public B, public C, public D {virtual void f();};
void f(D* pd) {
B* pb = dynamic_cast<B*>(pd); // cross cast
A* pa = pb; // upcast, implicit conversion
}
For each exercise, the type conversion must be solved using one specific type of casting.
Your choice will be checked during defense.
Conversion of scalar types
Turn-in directory : ex00/
Files to turn in : Makefile, *.cpp, *.{h, hpp}
Allowed functions : Any function to convert from a string to an int, a
float or a double. This will help, but won’t do the whole job.
- (우리가 직접 캐스팅 하라고 지정하는 명시적 (explicit)캐스팅)
ptr = (Something *)other_ptr; int_variable = (int)float_variable;
- But 말도 안되는 캐스팅에 대해서 컴파일러가 오류를 발생시키지 않는다.
static_cast :
우리가 흔히 생각하는, 언어적 차원에서 지원하는 일반적인 타입변환
const_cast:(포인터 및 참조형에서만 사용 가능하며)
객체의 상수성(const) 를 없애는 타입변환, 쉽게 말해 const int 가 int 로 바뀐다
dynamic_cast:
파생 클래스 사이에서의 다운캐스팅(->정확한 의미는 나중에~)
- Class의 포인터 간 형 변환 시, 안전하게 down casting을 위해 사용합니다.
- Class의 참조 변수간 형 변환 시, 안전하게 down casting을 위해 사용합니다.
- 단, parent에 virtual 함수가 존재해야 정상 동작합니다.
reinterpret_cast:
- (단 const를 사용하는 변환 대상은 사용할 수 없습니다.)
- 위험을 감수하고 하는 캐스팅으로 서로 관련이 없는 포인터들 사이의 캐스팅 등.
(원하는 캐스팅 종류)<바꾸려는 타입>(무엇을 바꿀 것인가?)
static_cast(float_variable);
static_cast로 float 타입의 float_variable이라는 변수를 int타입의 변수로 타입 변환.
Lastly,display the results as shown below.
If a conversion does not make any sense or overflows,
display a message to inform the user that the type conversion is impossible.
Include any header you need in order to handle numeric limits and special values.
./convert 0
char: Non displayable
int: 0
float: 0.0f
double: 0.0
./convert nan
char: impossible
int: impossible
float: nanf
double: nan
./convert 42.0f
char: '*'
int: 42
float: 42.0f
double: 42.0
Exercise : 01
Serialization
Turn-in directory : ex01/
Files to turn in : Makefile, *.cpp, *.{h, hpp}
Forbidden functions : None
Implement the following functions:
uintptr_t serialize(Data* ptr);
It takes a pointer and converts it to the unsigned integer type uintptr_t.
Data* deserialize(uintptr_t raw);
It takes an unsigned integer parameter and converts it to a pointer to Data.
Write a program to test that your functions works as expected.
You must create a non-empty (it means it has data members) Data structure.
Use serialize() on the address of the Data object and pass its return value to deserialize().
Then, ensure the return value of deserialize() compares equal to the original pointer.
Do not forget to turn in the files of your Data structure.
Exercise : 02
Identify real type
Turn-in directory : ex02/
Files to turn in : Makefile, *.cpp, *.{h, hpp}
Forbidden functions : std::typeinfo
Implement a Base class that has a public virtual destructor only.
Create three empty classes A, B and C, that publicly inherit from Base.
이클래스 4개는 캐노니컬 뭐시기 안 지켜도 됨.
Base * generate(void);
void identify(Base* p);
void identify(Base& p);
Including the typeinfo header is forbidden.
Write a program to test that everything works as expected.
파생 클래스 사이에서의 다운캐스팅