C++ Pimpl Idiom | "Pointer to Implementation" 가이드
이 글의 핵심
C++ 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 완벽 가이드 | 구현 은닉과 컴파일 시간 단축
- C++ Policy-Based Design | “정책 기반 설계” 가이드
- C++ PIMPL과 브릿지 패턴 | 구현 숨기기와 추상화 [#19-3]
관련 글
- C++ CRTP 패턴 |