C++ Dangling Reference | "댕글링 레퍼런스" 가이드
이 글의 핵심
C++ Dangling Reference에 대한 실전 가이드입니다.
Dangling Reference란?
소멸된 객체를 참조하는 레퍼런스
// ❌ 댕글링 레퍼런스
const std::string& func() {
std::string s = "Hello";
return s; // s는 함수 종료 시 소멸
}
int main() {
const std::string& ref = func();
// ref는 소멸된 객체 참조 (위험!)
}
발생 원인
// 1. 지역 변수 반환
const int& func1() {
int x = 10;
return x; // x 소멸
}
// 2. 임시 객체
const char* func2() {
return std::string("Hello").c_str(); // 임시 객체 소멸
}
// 3. 컨테이너 요소
const int& func3() {
std::vector<int> vec = {1, 2, 3};
return vec[0]; // vec 소멸
}
// 4. 포인터 역참조
int& func4() {
int* ptr = new int(10);
delete ptr;
return *ptr; // 해제된 메모리
}
실전 예시
예시 1: 함수 반환
#include <string>
// ❌ 지역 변수 레퍼런스 반환
const std::string& getName() {
std::string name = "Alice";
return name; // 위험!
}
// ✅ 값 반환
std::string getName() {
std::string name = "Alice";
return name; // 안전 (복사 또는 이동)
}
// ✅ 정적 변수 반환
const std::string& getStaticName() {
static std::string name = "Alice";
return name; // 안전
}
int main() {
auto name1 = getName(); // 안전
const auto& name2 = getStaticName(); // 안전
}
예시 2: 임시 객체
#include <vector>
// ❌ 임시 객체 레퍼런스
std::vector<int> getVector() {
return {1, 2, 3};
}
int main() {
// ❌ 임시 객체 즉시 소멸
const int& first = getVector()[0];
// getVector()의 임시 객체 소멸
// ✅ 컨테이너 저장
auto vec = getVector();
const int& first = vec[0]; // 안전
// ✅ 수명 연장
const auto& vec2 = getVector();
const int& first2 = vec2[0]; // 안전
}
예시 3: 컨테이너 요소
#include <map>
#include <string>
class Database {
private:
std::map<int, std::string> data;
public:
// ❌ 임시 맵 요소 반환
const std::string& getValue(int key) {
return data[key]; // data[key]가 없으면 임시 생성
}
// ✅ 값 반환 또는 optional
std::string getValue(int key) {
auto it = data.find(key);
return it != data.end() ? it->second : "";
}
// ✅ 포인터 반환
const std::string* getValuePtr(int key) {
auto it = data.find(key);
return it != data.end() ? &it->second : nullptr;
}
};
예시 4: 멤버 변수
class Widget {
private:
std::string name;
public:
Widget(const std::string& n) : name(n) {}
// ✅ 멤버 변수 레퍼런스 (안전)
const std::string& getName() const {
return name;
}
// ❌ 임시 객체 반환
const std::string& getUpperName() const {
return toUpper(name); // 임시 객체
}
// ✅ 값 반환
std::string getUpperName() const {
return toUpper(name);
}
private:
std::string toUpper(const std::string& s) const {
std::string result = s;
// 대문자 변환
return result;
}
};
자주 발생하는 문제
문제 1: 반복자 무효화
#include <vector>
std::vector<int> vec = {1, 2, 3};
// ❌ 반복자 무효화
auto& ref = vec[0];
vec.push_back(4); // 재할당 가능
// ref는 무효화될 수 있음
// ✅ 재할당 후 다시 참조
vec.push_back(4);
auto& ref = vec[0];
문제 2: 스마트 포인터
#include <memory>
class Data {
public:
int value = 42;
};
// ❌ 소유권 이전 후 참조
std::unique_ptr<Data> getData() {
return std::make_unique<Data>();
}
int main() {
auto ptr = getData();
int& ref = ptr->value;
ptr.reset(); // 메모리 해제
// ref는 댕글링
}
// ✅ shared_ptr 또는 값 복사
int main() {
auto ptr = std::make_shared<Data>();
int value = ptr->value; // 값 복사
ptr.reset();
// value는 안전
}
문제 3: 람다 캡처
#include <functional>
// ❌ 지역 변수 레퍼런스 캡처
std::function<int()> createGetter() {
int x = 10;
return [&x]() { return x; }; // x 소멸
}
int main() {
auto getter = createGetter();
int value = getter(); // 위험!
}
// ✅ 값 캡처
std::function<int()> createGetter() {
int x = 10;
return [x]() { return x; }; // 안전
}
문제 4: 체이닝
class Builder {
private:
std::string data;
public:
// ❌ 임시 객체 반환
Builder& append(const std::string& s) {
data += s;
return *this;
}
};
Builder createBuilder() {
return Builder();
}
int main() {
// ❌ 임시 객체 체이닝
auto& builder = createBuilder().append("Hello");
// createBuilder()의 임시 객체 소멸
// ✅ 값으로 받기
auto builder = createBuilder().append("Hello");
}
탐지 방법
// 1. 컴파일러 경고
// -Wreturn-local-addr (GCC)
// -Wreturn-stack-address (Clang)
// 2. 정적 분석 도구
// - Clang Static Analyzer
// - Cppcheck
// - PVS-Studio
// 3. 런타임 검사
// - AddressSanitizer
// - Valgrind
해결 방법
// 1. 값 반환
std::string func() {
std::string s = "Hello";
return s; // 복사 또는 이동
}
// 2. 스마트 포인터
std::shared_ptr<Data> func() {
return std::make_shared<Data>();
}
// 3. 출력 매개변수
void func(std::string& out) {
out = "Hello";
}
// 4. 정적 변수
const std::string& func() {
static std::string s = "Hello";
return s;
}
// 5. 멤버 변수
class Widget {
std::string name;
public:
const std::string& getName() const {
return name; // 안전
}
};
FAQ
Q1: Dangling Reference는 언제?
A:
- 지역 변수 반환
- 임시 객체 참조
- 소멸된 객체 접근
Q2: 탐지 방법은?
A:
- 컴파일러 경고
- 정적 분석 도구
- AddressSanitizer
Q3: 해결 방법은?
A:
- 값 반환
- 스마트 포인터
- 정적 변수
Q4: 성능 영향은?
A:
- 값 반환: RVO/이동으로 최적화
- 스마트 포인터: 약간의 오버헤드
Q5: 안전한 레퍼런스는?
A:
- 멤버 변수
- 정적 변수
- 매개변수
Q6: Dangling Reference 학습 리소스는?
A:
- “Effective C++”
- “C++ Core Guidelines”
- cppreference.com
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ Use After Free | “해제 후 사용” 가이드
- C++ Buffer Overflow | “버퍼 오버플로우” 가이드
- C++ Lifetime | “객체 수명” 가이드
관련 글
- C++ Buffer Overflow |
- C++ Lifetime |
- C++ optional |
- C++ Reference Collapsing |
- C++ 참조(Reference) 완벽 가이드 | lvalue·rvalue