Search code examples
c++pimpl-idiom

"api design for c++": c++ pimple access


I'm trying to understand a pimple example from the "api design for c++" book (page 70).

// autotimer.h
class AutoTimer
{
public:
    explicit AutoTimer(const std::string &name);
    AutoTimer();
    // allow access from other classes/functions in autotimer.cpp
    class Impl;
private:
    Impl* mImpl;
}

From the text and example I would assume thats possible to access members of AutoTimer::Impl from free functions declared in autotimer.cpp like free_f() in the example below.

// autotimer.cpp
class AutoTimer::Impl
{
 public:
    std::string s;
}

void free_f(AutoTimer a){
    std::cout << a.mImpl->s << std::endl;
}

However, I can't get this to work. Sadly the book doesn’t give any further details. So, how can I fix free_f() to get access to the private members of Impl?

To be me more explicit, the comment (and first example)

// allow access from other classes/functions in autotimer.cpp

is straight from the book "api design for c++" and I want to know what it means.


Solution

  • This is untested but should be legal C++ if your object is of standard layout type:

    void free_f(AutoTimer a){
        Impl* tmp = *reinterpret_cast<Impl**>(&a);
        std::cout << tmp->s << std::endl;
    }
    

    And since you work with with Pimpl you should pass references or pointers of type AutoTimer. Otherwise a temporary object will destroy your implementation object on destruction.

    http://en.cppreference.com/w/cpp/language/data_members#Standard_layout