TIL - 04(매직넘버, 구조체, 복사 생성자)

jh Seo·2024년 7월 29일

매직 넘버

하드코딩된 리터럴 상수값
ex) 3.14 * radius *radius
3.14라는 상수값대신 PI이런 식의 변수를 사용하는 것이 권장된다.

메모리에서 채워넣는 상수값을 일컫기도 한다.
ex) 0xcdcdcdcd 메모리 할당 후 초기화 되지 않은 힙 메모리

구조체

int값이 세 개 들어있는 구조체가 있을 때

  struct FStruct
  {
      int value1  = 10;
      int value2 = 20;
      int value3 = 30;
  }; 
FStruct* StructPointer = new FStruct();
int* Test = (int*)StructPointer + 0;
int* Test = (int*)StructPointer + 1;
int* Test = (int*)StructPointer + 2;

해당 구조체 포인터를 int*로 형변환 해준 후, +0 1 2로 value 1, 2 ,3에 접근할 수 있다.

복사 생성자 호출 경로

FParam CallByValue(FParam InParam)
{
	InParam.Value[0] = 1000;
	InParam.Value[1] = 2000;
	return InParam;
}

이런 함수가 있고,
복사생성자를 생성해주고,

FParam::FParam(const FParam& InOther)
	:A(InOther.A)
{
	std::cout << "FParam copy constructor";
	for (int i = 0; i < 1000; i++)
		this->Value[i] = InOther.Value[i];
}

대입연산자 =을 FParam구조체 안에 오버로딩해준 후,

void FParam::operator=(const FParam& InOther)
{
	std::cout << "FParam operator = ";
	for (int i = 0; i < 1000; i++)
		this->Value[i] = InOther.Value[i];

	A = InOther.A;
}

소멸자도 추가해준다.

FParam::~FParam()
{
		std::cout << "~FParam\n";
}

아래와 같이 호출하면 어떤 순서로 호출될까

FParam Param;
Param = CallByValue(Param);

답은
복사생성자가 먼저 호출되고 (parameter로 들어간 Param호출)
한번더 복사생성자가 호출된다. (CallByValue함수의 return값을 임시객체에 저장)
그리고 소멸자가 호출되고, (parameter로 생성된 FParam객체)
대입연산자가 실행되고,
다시 소멸자가 호출된다 (임시객체에 저장된 return 값)

profile
코딩 창고!

0개의 댓글