Is it possible to write an agile Pimpl in c++?

后端 未结 4 1495
無奈伤痛
無奈伤痛 2020-12-03 16:14

I\'ve been playing with the Pimpl idiom and reaping all sorts of benefits from it. The only thing I haven\'t been too keen on is the feeling I get when I define the function

4条回答
  •  庸人自扰
    2020-12-03 16:23

    There's no requirement to treat the IMPL object to the same rules & standards as an object declaration in the .h file. By allowing member variables to be public (via a struct declaration), you don't need to implement an unnecessary wrapper layer. This is generally safe, since only the .cpp file has access to IMPL anyway.

    Consider the following code that achieves the benefits of the PIMPL idiom without unnecessary code duplication:

    // x.h
    class X {
    public:
        X();
        ~X();
    
        X(const X&) = delete;
        X& operator =(const X&) = delete;
    
        void set(int val);
        int get() const;
    
    private:
        struct IMPL;
        IMPL* impl;
    };
    
    // x.cpp
    #include "x.h"
    
    struct X::IMPL {
        int val;
    };
    
    
    X::X() : impl(new IMPL) {}
    
    X::~X() { delete impl; }
    
    void X::set(int val)
    {
        impl->val = val;
    }
    
    int X::get() const
    {
        return impl->val;
    }
    
    // main.cpp
    #include 
    #include "x.h"
    
    int main (int, char *[])
    {
        X x;
        x.set(10);
        std::cout << x.get() << std::endl;
        return 0;
    }
    

提交回复
热议问题