본문으로 건너뛰기
Previous
Next
C++ Pimpl Idiom | 'Pointer to Implementation' 가이드

C++ Pimpl Idiom | 'Pointer to Implementation' 가이드

C++ Pimpl Idiom | 'Pointer to Implementation' 가이드

이 글의 핵심

C++ Pimpl Idiom: "Pointer to Implementation" 가이드. Pimpl Idiom이란?·실전 예시.

Pimpl Idiom이란?

구현을 포인터 뒤로 숨기는 패턴

// widget.h
class Widget {
public:
    Widget();
    ~Widget();
    void doSomething();
    
private:
    class Impl;  // 전방 선언
    std::unique_ptr<Impl> pImpl;  // 구현 포인터
};

// widget.cpp
class Widget::Impl {
public:
    void doSomething() {
        // 실제 구현
    }
    
private:
    // 내부 데이터
    int data;
    std::string name;
};

Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;

void Widget::doSomething() {
    pImpl->doSomething();
}

장점

// ✅ 컴파일 의존성 감소
// widget.h - 헤더 변경 없음
class Widget {
public:
    Widget();
    ~Widget();
    void doSomething();
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// widget.cpp - 구현만 변경
class Widget::Impl {
    // 내부 변경해도 헤더는 그대로
    // 클라이언트 재컴파일 불필요
};

실전 예시

예시 1: 기본 Pimpl

// person.h
#include <memory>
#include <string>

class Person {
public:
    Person(const std::string& name, int age);
    ~Person();
    
    // 복사/이동 연산자 선언
    Person(const Person& other);
    Person& operator=(const Person& other);
    Person(Person&& other) noexcept;
    Person& operator=(Person&& other) noexcept;
    
    std::string getName() const;
    int getAge() const;
    void setName(const std::string& name);
    void setAge(int age);
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// person.cpp
class Person::Impl {
public:
    Impl(const std::string& name, int age) 
        : name(name), age(age) {}
    
    std::string name;
    int age;
};

Person::Person(const std::string& name, int age)
    : pImpl(std::make_unique<Impl>(name, age)) {}

Person::~Person() = default;

Person::Person(const Person& other)
    : pImpl(std::make_unique<Impl>(*other.pImpl)) {}

Person& Person::operator=(const Person& other) {
    if (this != &other) {
        *pImpl = *other.pImpl;
    }
    return *this;
}

Person::Person(Person&& other) noexcept = default;
Person& Person::operator=(Person&& other) noexcept = default;

std::string Person::getName() const {
    return pImpl->name;
}

int Person::getAge() const {
    return pImpl->age;
}

void Person::setName(const std::string& name) {
    pImpl->name = name;
}

void Person::setAge(int age) {
    pImpl->age = age;
}

예시 2: 라이브러리 인터페이스

// database.h
#include <memory>
#include <string>
#include <vector>

class Database {
public:
    Database(const std::string& connectionString);
    ~Database();
    
    Database(const Database&) = delete;
    Database& operator=(const Database&) = delete;
    
    void connect();
    void disconnect();
    bool isConnected() const;
    
    void execute(const std::string& query);
    std::vector<std::string> query(const std::string& sql);
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// database.cpp
#include <iostream>
// 외부 라이브러리 헤더 (클라이언트에 노출 안됨)
// #include <mysql/mysql.h>

class Database::Impl {
public:
    Impl(const std::string& connStr) 
        : connectionString(connStr), connected(false) {}
    
    void connect() {
        std::cout << "연결: " << connectionString << std::endl;
        connected = true;
    }
    
    void disconnect() {
        std::cout << "연결 해제" << std::endl;
        connected = false;
    }
    
    bool isConnected() const {
        return connected;
    }
    
    void execute(const std::string& query) {
        std::cout << "실행: " << query << std::endl;
    }
    
    std::vector<std::string> query(const std::string& sql) {
        std::cout << "쿼리: " << sql << std::endl;
        return {"결과1", "결과2"};
    }
    
private:
    std::string connectionString;
    bool connected;
    // MYSQL* connection;  // 외부 라이브러리 타입
};

Database::Database(const std::string& connectionString)
    : pImpl(std::make_unique<Impl>(connectionString)) {}

Database::~Database() = default;

void Database::connect() {
    pImpl->connect();
}

void Database::disconnect() {
    pImpl->disconnect();
}

bool Database::isConnected() const {
    return pImpl->isConnected();
}

void Database::execute(const std::string& query) {
    pImpl->execute(query);
}

std::vector<std::string> Database::query(const std::string& sql) {
    return pImpl->query(sql);
}

예시 3: 플랫폼별 구현

// window.h
#include <memory>
#include <string>

class Window {
public:
    Window(const std::string& title, int width, int height);
    ~Window();
    
    void show();
    void hide();
    void setTitle(const std::string& title);
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// window_win32.cpp (Windows)
#ifdef _WIN32
// #include <windows.h>

class Window::Impl {
public:
    Impl(const std::string& title, int width, int height) {
        // HWND hwnd = CreateWindow(...);
        std::cout << "Windows 창 생성: " << title << std::endl;
    }
    
    void show() {
        // ShowWindow(hwnd, SW_SHOW);
        std::cout << "Windows 창 표시" << std::endl;
    }
    
    void hide() {
        std::cout << "Windows 창 숨김" << std::endl;
    }
    
    void setTitle(const std::string& title) {
        std::cout << "Windows 제목 변경: " << title << std::endl;
    }
    
private:
    // HWND hwnd;
};
#endif

// window_x11.cpp (Linux)
#ifdef __linux__
// #include <X11/Xlib.h>

class Window::Impl {
public:
    Impl(const std::string& title, int width, int height) {
        std::cout << "X11 창 생성: " << title << std::endl;
    }
    
    void show() {
        std::cout << "X11 창 표시" << std::endl;
    }
    
    void hide() {
        std::cout << "X11 창 숨김" << std::endl;
    }
    
    void setTitle(const std::string& title) {
        std::cout << "X11 제목 변경: " << title << std::endl;
    }
    
private:
    // Display* display;
    // Window window;
};
#endif

Window::Window(const std::string& title, int width, int height)
    : pImpl(std::make_unique<Impl>(title, width, height)) {}

Window::~Window() = default;

void Window::show() {
    pImpl->show();
}

void Window::hide() {
    pImpl->hide();
}

void Window::setTitle(const std::string& title) {
    pImpl->setTitle(title);
}

예시 4: ABI 안정성

// library_v1.h (버전 1)
class MyClass {
public:
    MyClass();
    ~MyClass();
    void func1();
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// library_v2.h (버전 2 - 헤더 동일!)
class MyClass {
public:
    MyClass();
    ~MyClass();
    void func1();
    void func2();  // 새 함수 추가
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// library_v2.cpp
class MyClass::Impl {
public:
    void func1() {
        std::cout << "func1" << std::endl;
    }
    
    void func2() {  // 새 구현
        std::cout << "func2" << std::endl;
    }
    
private:
    int newData;  // 새 멤버 추가 (ABI 영향 없음)
};

Fast Pimpl (최적화)

// 작은 객체는 스택 할당
class Widget {
public:
    Widget();
    ~Widget();
    
private:
    static constexpr size_t ImplSize = 64;
    alignas(8) char implStorage[ImplSize];
    
    class Impl;
    Impl* pImpl() {
        return reinterpret_cast<Impl*>(implStorage);
    }
};

자주 발생하는 문제

문제 1: 소멸자 정의 누락

// ❌ 헤더에서 소멸자 정의
class Widget {
public:
    ~Widget() = default;  // 에러: Impl 불완전 타입
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// ✅ cpp 파일에서 정의
// widget.h
class Widget {
public:
    ~Widget();
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// widget.cpp
Widget::~Widget() = default;

문제 2: 복사 연산자

// ❌ 기본 복사 (얕은 복사)
class Widget {
public:
    // 컴파일러 생성 복사는 unique_ptr 복사 불가
    
private:
    std::unique_ptr<Impl> pImpl;
};

// ✅ 명시적 복사 구현
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;
}

문제 3: 성능 오버헤드

// ❌ 간접 호출 오버헤드
void Widget::doSomething() {
    pImpl->doSomething();  // 간접 호출
}

// ✅ 인라인 가능한 함수는 직접 구현
class Widget {
public:
    int getValue() const { return value; }  // 인라인
    
private:
    int value;  // 간단한 데이터는 직접
    class Impl;
    std::unique_ptr<Impl> pImpl;  // 복잡한 구현만
};

문제 4: 전방 선언 제약

// ❌ Impl 타입 직접 사용
class Widget {
public:
    Impl getImpl() const;  // 에러: 불완전 타입
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// ✅ 포인터/참조만 사용
class Widget {
public:
    const Impl* getImpl() const;  // OK
    
private:
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

Pimpl vs 다른 패턴

// Pimpl: 구현 숨기기
class Widget {
    class Impl;
    std::unique_ptr<Impl> pImpl;
};

// Bridge: 추상화와 구현 분리
class Widget {
    std::unique_ptr<WidgetImpl> impl;  // 인터페이스
};

// Strategy: 알고리즘 교체
class Widget {
    std::unique_ptr<Strategy> strategy;
};

FAQ

Q1: Pimpl은 언제 사용?

A:

  • 컴파일 의존성 감소
  • ABI 안정성 필요
  • 구현 숨기기

Q2: 성능 영향은?

A:

  • 간접 호출 오버헤드
  • 메모리 할당 비용
  • 캐시 미스 가능

Q3: unique_ptr vs shared_ptr?

A:

  • unique_ptr: 일반적 (권장)
  • shared_ptr: 공유 필요 시

Q4: 복사는?

A: 명시적 구현 필요. *pImpl = *other.pImpl

Q5: 언제 사용 지양?

A:

  • 간단한 클래스
  • 성능 중요
  • 헤더 온리 라이브러리

Q6: Pimpl 학습 리소스는?

A:

  • “Effective Modern C++”
  • “API Design for C++”
  • cppreference.com

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

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

관련 글

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

이 부록은 앞선 본문에서 다룬 주제(「C++ Pimpl Idiom | ‘Pointer to Implementation’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(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 | ‘Pointer to Implementation’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  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 등으로 검색하시면 이 글이 도움이 됩니다.