본문으로 건너뛰기
Previous
Next
C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축

C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축

C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축

이 글의 핵심

문제: Widget 클래스가 내부적으로 HeavyLibrary를 사용합니다. widget.h에 #include heavy_library.h를 쓰면, Widget을 사용하는 모든 파일이 heavy_library.h에 의존하게 됩니다. heavy_library.h가 바뀌면 전체 프로젝트가 재컴파일됩니다.

Pimpl Idiom이란? 왜 필요한가

문제 시나리오: 헤더 변경 시 전체 재컴파일

문제: Widget 클래스가 내부적으로 HeavyLibrary를 사용합니다. widget.h#include "heavy_library.h"를 쓰면, Widget을 사용하는 모든 파일heavy_library.h에 의존하게 됩니다. heavy_library.h가 바뀌면 전체 프로젝트가 재컴파일됩니다. widget.h (나쁜 예):

#include "heavy_library.h"  // 수천 줄 헤더
// 타입 정의
class Widget {
public:
    void doSomething();
private:
    HeavyLibrary lib;  // 헤더에 노출
};

해결: Pimpl(Pointer to Implementation)은 구현을 .cpp로 숨겨 헤더 의존성을 끊습니다. 헤더에는 전방 선언포인터만 두고, 구현은 .cpp에 둡니다. widget.h (좋은 예):

#include <memory>
class Widget {
public:
    Widget();
    ~Widget();
    void doSomething();
    
private:
    struct Impl;  // 전방 선언
    std::unique_ptr<Impl> pImpl;
};

widget.cpp:

#include "widget.h"
#include "heavy_library.h"  // .cpp에만
// 타입 정의
struct Widget::Impl {
    HeavyLibrary lib;
};
Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
void Widget::doSomething() {
    pImpl->lib.process();
}
// 실행 예제
flowchart TD
    subgraph without[Pimpl 없이]
        h1["widget.h\n#include heavy_library.h"]
        u1["user1.cpp\n#include widget.h"]
        u2["user2.cpp\n#include widget.h"]
        recomp["heavy_library.h 변경\n→ 전체 재컴파일"]
    end
    subgraph with[Pimpl 사용]
        h2["widget.h\nstruct Impl; (전방 선언)"]
        cpp["widget.cpp\n#include heavy_library.h"]
        u3["user1.cpp\n#include widget.h"]
        u4["user2.cpp\n#include widget.h"]
        recomp2["heavy_library.h 변경\n→ widget.cpp만 재컴파일"]
    end
    h1 --> u1
    h1 --> u2
    h1 --> recomp
    h2 --> u3
    h2 --> u4
    cpp --> recomp2

1. 기본 구조

최소 Pimpl

widget.h:

#pragma once
#include <memory>
class Widget {
public:
    Widget();
    ~Widget();
    
    void doSomething();
    
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};

widget.cpp:

#include "widget.h"
#include <iostream>
struct Widget::Impl {
    int data = 42;
    
    void internalMethod() {
        std::cout << "Data: " << data << '\n';
    }
};
Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;  // unique_ptr이 자동 삭제
void Widget::doSomething() {
    pImpl->internalMethod();
}

main.cpp:

#include "widget.h"
int main() {
    Widget w;
    w.doSomething();  // "Data: 42"
}

2. 복사와 이동

복사 구현

// widget.h
class Widget {
public:
    Widget();
    ~Widget();
    
    Widget(const Widget& other);
    Widget& operator=(const Widget& other);
    
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// widget.cpp
Widget::Widget(const Widget& other)
    : pImpl(std::make_unique<Impl>(*other.pImpl)) {}
Widget& Widget::operator=(const Widget& other) {
    if (this != &other) {
        *pImpl = *other.pImpl;
    }
    return *this;
}

이동 구현

// widget.h
class Widget {
public:
    Widget();
    ~Widget();
    
    Widget(Widget&& other) noexcept;
    Widget& operator=(Widget&& other) noexcept;
    
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// widget.cpp
Widget::Widget(Widget&& other) noexcept = default;
Widget& Widget::operator=(Widget&& other) noexcept = default;

3. ABI 안정성

문제: 헤더 변경 시 ABI 깨짐

// v1.0: widget.h
class Widget {
private:
    int data;  // 4바이트
};
// v1.1: 멤버 추가
class Widget {
private:
    int data;
    double extra;  // 8바이트 추가 → sizeof(Widget) 변경!
};
// v1.0으로 컴파일된 코드와 호환 불가

해결: Pimpl로 ABI 안정화

// v1.0, v1.1 모두 동일한 헤더
class Widget {
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;  // 포인터 크기 불변
};
// v1.1: .cpp에서만 변경
struct Widget::Impl {
    int data;
    double extra;  // 추가해도 ABI 안정
};

결과: 헤더는 변하지 않아 바이너리 호환성이 유지됩니다.

4. 자주 발생하는 문제와 해결법

문제 1: 소멸자 인라인 정의

증상: error: invalid application of 'sizeof' to an incomplete type. 원인: 헤더에서 ~Widget() = default를 인라인으로 정의하면, Impl이 불완전 타입이라 unique_ptr 소멸자가 컴파일 에러를 냅니다.

// ❌ 잘못된 사용: 헤더에서 인라인
class Widget {
public:
    ~Widget() = default;  // Error: Impl 불완전
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// ✅ 올바른 사용: .cpp에서 정의
// widget.h
class Widget {
public:
    ~Widget();
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// widget.cpp
Widget::~Widget() = default;  // OK: Impl 완전한 타입

문제 2: 복사 생성자 누락

증상: error: use of deleted function. 원인: unique_ptr은 복사 불가능하므로, 복사 생성자를 명시적으로 구현해야 합니다.

// ❌ 잘못된 사용: 복사 생성자 없음
Widget w1;
Widget w2 = w1;  // Error: unique_ptr 복사 불가
// ✅ 올바른 사용: 복사 생성자 구현
Widget::Widget(const Widget& other)
    : pImpl(std::make_unique<Impl>(*other.pImpl)) {}

문제 3: 전방 선언 불완전

증상: error: member access into incomplete type. 원인: 헤더에서 Impl의 멤버에 접근하려 함.

// ❌ 잘못된 사용: 헤더에서 접근
class Widget {
public:
    int getData() const { return pImpl->data; }  // Error: Impl 불완전
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// ✅ 올바른 사용: .cpp에서 구현
// widget.h
class Widget {
public:
    int getData() const;
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// widget.cpp
int Widget::getData() const {
    return pImpl->data;  // OK
}

5. 프로덕션 패턴

패턴 1: shared_ptr로 복사 비용 절감

// 복사가 빈번한 경우 shared_ptr 사용
class Widget {
private:
    struct Impl;
    std::shared_ptr<Impl> pImpl;
};
Widget::Widget() : pImpl(std::make_shared<Impl>()) {}
// 복사는 포인터 복사만 (얕은 복사)
Widget::Widget(const Widget&) = default;

패턴 2: Fast Pimpl (작은 객체 최적화)

// 작은 Impl은 unique_ptr 오버헤드가 부담
// → 직접 메모리 관리
class Widget {
private:
    static constexpr size_t IMPL_SIZE = 64;
    alignas(std::max_align_t) char impl_buffer[IMPL_SIZE];
    
    struct Impl;
    Impl* pImpl;
};
Widget::Widget() {
    static_assert(sizeof(Impl) <= IMPL_SIZE);
    pImpl = new (impl_buffer) Impl();
}
Widget::~Widget() {
    pImpl->~Impl();
}

패턴 3: 조건부 Pimpl

// 플랫폼별로 다른 구현
// widget.h
class Widget {
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};
// widget_windows.cpp
#ifdef _WIN32
struct Widget::Impl {
    HWND hwnd;
    // Windows 전용 구현
};
#endif
// widget_linux.cpp
#ifdef __linux__
struct Widget::Impl {
    int fd;
    // Linux 전용 구현
};
#endif

6. 완전한 예제: HTTP 클라이언트

http_client.h:

#pragma once
#include <memory>
#include <string>
#include <map>
class HttpClient {
public:
    HttpClient();
    ~HttpClient();
    
    HttpClient(const HttpClient&);
    HttpClient& operator=(const HttpClient&);
    
    HttpClient(HttpClient&&) noexcept;
    HttpClient& operator=(HttpClient&&) noexcept;
    
    void setTimeout(int seconds);
    void setHeader(const std::string& key, const std::string& value);
    
    std::string get(const std::string& url);
    std::string post(const std::string& url, const std::string& body);
    
private:
    struct Impl;
    std::unique_ptr<Impl> pImpl;
};

http_client.cpp:

#include "http_client.h"
#include <curl/curl.h>  // 무거운 라이브러리, .cpp에만
#include <iostream>
struct HttpClient::Impl {
    CURL* curl = nullptr;
    int timeout = 30;
    std::map<std::string, std::string> headers;
    
    Impl() {
        curl = curl_easy_init();
    }
    
    ~Impl() {
        if (curl) curl_easy_cleanup(curl);
    }
    
    std::string perform(const std::string& url) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
        
        // 헤더 설정
        struct curl_slist* header_list = nullptr;
        for (const auto& [key, value] : headers) {
            std::string header = key + ": " + value;
            header_list = curl_slist_append(header_list, header.c_str());
        }
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);
        
        // 요청 수행
        CURLcode res = curl_easy_perform(curl);
        
        curl_slist_free_all(header_list);
        
        if (res != CURLE_OK) {
            throw std::runtime_error(curl_easy_strerror(res));
        }
        
        return "Response data";
    }
};
HttpClient::HttpClient() : pImpl(std::make_unique<Impl>()) {}
HttpClient::~HttpClient() = default;
HttpClient::HttpClient(const HttpClient& other)
    : pImpl(std::make_unique<Impl>(*other.pImpl)) {}
HttpClient& HttpClient::operator=(const HttpClient& other) {
    if (this != &other) {
        *pImpl = *other.pImpl;
    }
    return *this;
}
HttpClient::HttpClient(HttpClient&&) noexcept = default;
HttpClient& HttpClient::operator=(HttpClient&&) noexcept = default;
void HttpClient::setTimeout(int seconds) {
    pImpl->timeout = seconds;
}
void HttpClient::setHeader(const std::string& key, const std::string& value) {
    pImpl->headers[key] = value;
}
std::string HttpClient::get(const std::string& url) {
    return pImpl->perform(url);
}
std::string HttpClient::post(const std::string& url, const std::string& body) {
    curl_easy_setopt(pImpl->curl, CURLOPT_POSTFIELDS, body.c_str());
    return pImpl->perform(url);
}

main.cpp:

#include "http_client.h"
#include <iostream>
// 변수 선언 및 초기화
int main() {
    HttpClient client;
    client.setTimeout(60);
    client.setHeader("Content-Type", "application/json");
    
    try {
        std::string response = client.get("https://api.example.com/data");
        std::cout << "Response: " << response << '\n';
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << '\n';
    }
}

장점: main.cppcurl.h를 include하지 않아도 되고, curl.h가 변경되어도 http_client.cpp만 재컴파일됩니다.

7. 성능 고려사항

오버헤드

항목비용
메모리포인터 크기 (8바이트) + 힙 할당
접근간접 참조 1회 (포인터 역참조)
캐시캐시 미스 가능성 증가

언제 사용하지 말아야 하나

  • 성능이 매우 중요한 핫 패스: 간접 참조 비용이 부담될 수 있음
  • 작고 간단한 클래스: Pimpl 오버헤드가 더 클 수 있음
  • 헤더 의존성이 적은 경우: Pimpl의 이점이 적음

언제 사용해야 하나

  • 컴파일 시간이 긴 대형 프로젝트
  • ABI 안정성이 중요한 라이브러리
  • 무거운 헤더 의존성을 숨기고 싶을 때

정리

개념설명
PimplPointer to Implementation
목적컴파일 의존성 감소, ABI 안정성
구조헤더에 전방 선언 + 포인터, .cpp에 구현
복사명시적 구현 필요
이동= default 가능
오버헤드간접 참조, 힙 할당
Pimpl Idiom은 대형 프로젝트에서 컴파일 시간을 단축하고, 라이브러리에서 ABI 안정성을 보장하는 강력한 패턴입니다.

FAQ

Q1: Pimpl은 언제 쓰나요?

A: 컴파일 시간이 긴 프로젝트, ABI 안정성이 중요한 라이브러리, 무거운 헤더 의존성을 숨기고 싶을 때 사용합니다.

Q2: 성능 오버헤드는?

A: 간접 참조 1회, 힙 할당 비용이 있습니다. 핫 패스가 아니면 무시할 수 있는 수준입니다.

Q3: 소멸자를 왜 .cpp에 정의하나요?

A: 헤더에서 = default로 인라인 정의하면, Impl이 불완전 타입이라 unique_ptr 소멸자가 컴파일 에러를 냅니다. .cpp에서 정의하면 Impl이 완전한 타입이므로 OK입니다.

Q4: shared_ptr vs unique_ptr?

A: unique_ptr이 기본입니다. 복사가 빈번하면 shared_ptr을 고려하세요 (얕은 복사).

Q5: Fast Pimpl은 뭔가요?

A: 작은 Impl을 힙이 아닌 클래스 내부 버퍼에 placement new로 생성해 힙 할당 비용을 없애는 최적화입니다.

Q6: Pimpl 학습 리소스는?

A:

  • “Effective C++” by Scott Meyers (Item 31)
  • “C++ Coding Standards” by Herb Sutter
  • GotW #28: Pimpl 한 줄 요약: Pimpl로 컴파일 의존성을 줄이고 ABI 안정성을 확보할 수 있습니다. 다음으로 CRTP를 읽어보면 좋습니다.

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ Pimpl Idiom 완벽 가이드 | 구현 은닉과 컴파일 시간 단축」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, pimpl, idiom, encapsulation, abi, compilation 등으로 검색하시면 이 글이 도움이 됩니다.