Server/C++

Pass by Value, Pointer, Reference

Juzdalua 2024. 7. 31. 20:25

함수에 매개변수를 넘겨줄 때, 세가지 방법이 존재한다.

// Pass by Value
void fooV(int b){
	int c = b + 1;
}

// Pass by Pointer
void fooP(int* pB){
	int c = *pB + 1;
}

// Pass by Reference
void fooR(const int& b){
	int c = b + 1;
}

int main(){
	int a = 0;

	fooV(a);
	fooP(&a);
	fooR(a);

	return 0;
}

 

Value값을 그대로 넘겨주면 변수 b에 복제된 0이 할당되고 c에 1이 할당된다.

// Pass by Value

int a = 0;
int b = 0;
int c = 1;

 

포인터나 레퍼런스를 활용하면 데이터를 직접 메모리에 복제하지 않고, 기존 데이터가 저장된 주소값만 할당 받기 때문에 메모리 누수를 방지할 수 있다.

 

Pass by Pointer와 Pass by Reference는 어셈블리언어로 완벽하게 동일하게 동작한다.

 

포인터를 직접 사용할 일이 없다면, Reference를 활용하는 것이 버그 방지에 조금이나마 좋다.

'Server > C++' 카테고리의 다른 글

Lock을 사용한 Stack과 Queue 템플릿  (0) 2024.08.01
클래스 연산자 로버로딩  (0) 2024.07.31
L Value, R Value, Reference  (0) 2024.07.31
TLS(Thread Local Storage)  (0) 2024.07.31
메모리 모델과 원자적(atomic) 연산  (0) 2024.07.31