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

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

이 글의 핵심

C++ Pimpl Idiom 완벽 가이드에 대해 정리한 개발 블로그 글입니다. 문제: Widget 클래스가 내부적으로 HeavyLibrary를 사용합니다. widget.h에 #include "heavy_library.h"를 쓰면, Widget을 사용하는 모든 파일이 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. 기본 구조
  2. 복사와 이동
  3. ABI 안정성
  4. 자주 발생하는 문제와 해결법
  5. 프로덕션 패턴
  6. 완전한 예제: HTTP 클라이언트
  7. 성능 고려사항

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++ 스마트 포인터 | unique_ptr/shared_ptr “메모리 안전” 가이드

관련 글

  • C++ Pimpl Idiom |