Skip to content

Instantly share code, notes, and snippets.

@mtao
Last active May 5, 2020 19:10
Show Gist options
  • Save mtao/662875b1788ba45d19a11168dfe1e076 to your computer and use it in GitHub Desktop.
Save mtao/662875b1788ba45d19a11168dfe1e076 to your computer and use it in GitHub Desktop.
A simple example of the Pimpl pattern using unique_ptr to store the object. This example is intended to show that although I want to hide the implementation, `unique_ptr` wants to call `A_impl::~A_impl` which isn't available from the header and that this issue can be ameliorated by defining `A::~A() = default;` in the implementation
#include "Pimpl.h"
int main(int argc, char * argv[]) {
A a;
a.f();
}
#include "A.h"
#include <iostream>
class A_impl {
public:
void f() const {
std::cout << "F!" << std::endl;
}
};
A::A(): _obj{std::make_unique<A_impl>()} {}
//Can still use the implicitly-declared destructor with = default!
A::~A() = default;
void A::f() const {
assert(_obj);
_obj->f();
}
#pragma once
#include <memory>
// I don't want to expose this class to the public
class A_impl;
class A {
public:
A();
// This requires that Imported be fully defined in the header
//~A() = default;
// So instead we have to implement it
~A();
void f() const;
private:
std::unique_ptr<A_impl> _obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment