포인터와 주소
Pointer는 호환되는 object의 address를 담습니다.
포인터와 주소이란?
Pointer는 호환되는 object의 address를 담습니다.
주소를 저장하고 dereference하여 원본 객체를 변경합니다.
중요한 점
- 포인터는 살아 있는 호환 객체를 가리키거나 null이어야 합니다.
- 소유한 allocation은 정확히 한 번 해제하세요.
- Ownership과 const를 명확히 표현하세요.
C와 C++ 코드 예제
C
main.c
#include <stdio.h>
int main(void) {
int score = 70;
int *score_ptr = &score;
*score_ptr += 5;
printf("score=%d same-address=%s\n", score,
score_ptr == &score ? "yes" : "no");
return 0;
}
score=75 same-address=yes
C++
main.cpp
#include <iostream>
int main() {
int score = 70;
int* score_ptr = &score;
*score_ptr += 5;
std::cout << "score=" << score << " same-address="
<< std::boolalpha << (score_ptr == &score) << '\n';
}
score=75 same-address=true
C와 C++ 비교
C는 raw pointer를 직접 사용합니다. C++도 non-owning access에 쓰지만 null이 필요 없으면 reference가 적합합니다.
C
Ownership과 cleanup은 개발자가 지켜야 하는 규칙입니다.
C++
Container와 RAII가 ownership과 cleanup을 lifetime에 연결합니다.
연습 문제
두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.
- null과 할당 실패를 테스트하세요.
- AddressSanitizer와 UndefinedBehaviorSanitizer를 실행하세요.
- 각 pointer의 ownership을 문서화하세요.