Last active
May 5, 2020 19:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Pimpl.h" | |
int main(int argc, char * argv[]) { | |
A a; | |
a.f(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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