简体   繁体   中英

Alternative PImpl Idiom - advantages vs disadvantages?

The traditional PImpl Idiom is like this:

#include <memory>

struct Blah
{
    //public interface declarations

private:
    struct Impl;
    std::unique_ptr<Impl> impl;
};

//in source implementation file:

struct Blah::Impl
{
    //private data
};
//public interface definitions

However, for fun, I tried to use composition with private inheritance instead:

[Test.h]

#include <type_traits>
#include <memory>

template<typename Derived>
struct PImplMagic
{
    PImplMagic()
    {
        static_assert(std::is_base_of<PImplMagic, Derived>::value,
                      "Template parameter must be deriving class");
    }
//protected: //has to be public, unfortunately
    struct Impl;
};

struct Test : private PImplMagic<Test>,
              private std::unique_ptr<PImplMagic<Test>::Impl>
{
    Test();
    ~Test();
    void f();
};

[first translation unit]

#include "Test.h"
int main()
{
    Test t;
    t.f();
}

[second translation unit]

#include <iostream>
#include <memory>

#include "Test.h"

template<>
struct PImplMagic<Test>::Impl
{
    Impl()
    {
        std::cout << "It works!" << std::endl;
    }
    int x = 7;
};

Test::Test()
: std::unique_ptr<Impl>(new Impl)
{
}

Test::~Test() // required for `std::unique_ptr`'s dtor
{}

void Test::f()
{
    std::cout << (*this)->x << std::endl;
}

http://ideone.com/WcxJu2

I like the way this alternate version works, however I'm curious if it has any major drawbacks over the traditional version?

EDIT: DyP has kindly provided yet another version , which is even 'prettier'.

From what I understand, one of the reasons to use a pimpl idiom is to hide functionality details from the user of your interface. In your composition with private inheritance example, I believe you are exposing your implementation details to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM