[2026] C++ Pimpl Idiom Complete Guide | Pointer to Implementation Pattern
이 글의 핵심
Master C++ Pimpl idiom for hiding implementation details: faster builds, stable ABI, unique_ptr usage, rule of five, platform-specific implementations, and library interfaces.
What is Pimpl Idiom?
Pointer to implementation: public class holds std::unique_ptr<Impl>; Impl is defined only in .cpp, hiding implementation details from header.
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// widget.h
class Widget {
public:
Widget();
~Widget();
void doSomething();
private:
class Impl; // Forward declaration
std::unique_ptr<Impl> pImpl; // Implementation pointer
};
// widget.cpp
class Widget::Impl {
public:
void doSomething() {
// Actual implementation
}
private:
// Internal data
int data;
std::string name;
};
Widget::Widget() : pImpl(std::make_unique<Impl>()) {}
Widget::~Widget() = default;
void Widget::doSomething() {
pImpl->doSomething();
}
Benefits
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ✅ Reduced compilation dependencies
// widget.h - No header changes
class Widget {
public:
Widget();
~Widget();
void doSomething();
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// widget.cpp - Only implementation changes
class Widget::Impl {
// Internal changes don't affect header
// No client recompilation needed
};
Key advantages:
- Faster builds: Clients don’t include heavy private headers
- ABI flexibility: Add private members without recompiling all users (within limits)
- Implementation hiding: Hide platform-specific or proprietary code
Practical Examples
Example 1: Basic Pimpl
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며, 에러 처리를 통해 안정성을 확보합니다, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// person.h
#include <memory>
#include <string>
class Person {
public:
Person(const std::string& name, int age);
~Person();
// Copy/move operators declaration
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;
}
Example 2: Library Interface
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// 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>
// External library headers (not exposed to clients)
// #include <mysql/mysql.h>
class Database::Impl {
public:
Impl(const std::string& connStr)
: connectionString(connStr), connected(false) {}
void connect() {
std::cout << "Connecting: " << connectionString << std::endl;
connected = true;
}
void disconnect() {
std::cout << "Disconnecting" << std::endl;
connected = false;
}
bool isConnected() const {
return connected;
}
void execute(const std::string& query) {
std::cout << "Executing: " << query << std::endl;
}
std::vector<std::string> query(const std::string& sql) {
std::cout << "Query: " << sql << std::endl;
return {"result1", "result2"};
}
private:
std::string connectionString;
bool connected;
// MYSQL* connection; // External library type
};
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);
}
Example 3: Platform-Specific Implementation
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// 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 window created: " << title << std::endl;
}
void show() {
// ShowWindow(hwnd, SW_SHOW);
std::cout << "Windows window shown" << std::endl;
}
void hide() {
std::cout << "Windows window hidden" << std::endl;
}
void setTitle(const std::string& title) {
std::cout << "Windows title changed: " << 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 window created: " << title << std::endl;
}
void show() {
std::cout << "X11 window shown" << std::endl;
}
void hide() {
std::cout << "X11 window hidden" << std::endl;
}
void setTitle(const std::string& title) {
std::cout << "X11 title changed: " << 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);
}
Example 4: ABI Stability
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// library_v1.h (Version 1)
class MyClass {
public:
MyClass();
~MyClass();
void func1();
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// library_v2.h (Version 2 - Header unchanged!)
class MyClass {
public:
MyClass();
~MyClass();
void func1();
void func2(); // New function added
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// library_v2.cpp
class MyClass::Impl {
public:
void func1() {
std::cout << "func1" << std::endl;
}
void func2() { // New implementation
std::cout << "func2" << std::endl;
}
private:
int newData; // New member added (no ABI impact)
};
Fast Pimpl (Optimization)
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// Stack allocation for small objects
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);
}
};
Small Buffer Optimization: For tiny Impl objects, inline storage avoids heap allocation. Advanced technique—measure first.
Common Issues
Issue 1: Missing destructor definition
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ❌ Defining destructor in header
class Widget {
public:
~Widget() = default; // Error: Impl incomplete type
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// ✅ Define in cpp file
// widget.h
class Widget {
public:
~Widget();
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// widget.cpp
Widget::~Widget() = default;
Issue 2: Copy operators
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ❌ Default copy (shallow copy)
class Widget {
public:
// Compiler-generated copy can't copy unique_ptr
private:
std::unique_ptr<Impl> pImpl;
};
// ✅ Explicit copy implementation
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;
}
Issue 3: Performance overhead
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ❌ Indirect call overhead
void Widget::doSomething() {
pImpl->doSomething(); // Indirect call
}
// ✅ Keep inlinable functions direct
class Widget {
public:
int getValue() const { return value; } // Inline
private:
int value; // Simple data direct
class Impl;
std::unique_ptr<Impl> pImpl; // Only complex implementation
};
Issue 4: Forward declaration constraints
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// ❌ Using Impl type directly
class Widget {
public:
Impl getImpl() const; // Error: incomplete type
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
// ✅ Use pointer/reference only
class Widget {
public:
const Impl* getImpl() const; // OK
private:
class Impl;
std::unique_ptr<Impl> pImpl;
};
Pimpl vs Other Patterns
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
// Pimpl: Hide implementation
class Widget {
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Bridge: Separate abstraction and implementation
class Widget {
std::unique_ptr<WidgetImpl> impl; // Interface
};
// Strategy: Algorithm replacement
class Widget {
std::unique_ptr<Strategy> strategy;
};
FAQ
Q1: When to use Pimpl?
A:
- Reduce compilation dependencies
- Need ABI stability
- Hide implementation details
Q2: Performance impact?
A:
- Indirect call overhead
- Memory allocation cost
- Possible cache misses
Q3: unique_ptr vs shared_ptr?
A:
- unique_ptr: General case (recommended)
- shared_ptr: When sharing needed
Q4: How to handle copying?
A: Need explicit implementation. *pImpl = *other.pImpl
Q5: When to avoid?
A:
- Simple classes
- Performance-critical code
- Header-only libraries
Q6: Pimpl learning resources?
A:
- “Effective Modern C++”
- “API Design for C++”
- cppreference.com
Related Articles
- C++ Pimpl Idiom Complete Guide | Implementation Hiding & Faster Compilation
- C++ Policy-Based Design Complete Guide
- C++ PIMPL and Bridge Pattern | Implementation Hiding & Abstraction [#19-3]
Related Posts
Keywords
C++, pimpl, opaque pointer, encapsulation, ABI, compilation firewall, implementation hiding