Search code examples
c++pimpl-idiom

How do you exchange private data with Pimpl without exposing your internals?


If you have an object B that needs a copy of a private member of an object A, and the private member is hidden by a Pimpl, how do you make it happen without exposing your internals? // Foo.h

class Foo
{
private :
  struct impl ;
  impl * pimpl ;
};

// Foo.cpp
struct impl { std::string data; }

//main.cpp
Foo A;
Foo B;
// I want A::pimpl->data copied to B::pimpl->data and I don't want std::string exposed in my Foo header.

Solution

  • // header
    class Foo
    {
        public:
           void Copy( const Foo & );
        private :
           struct impl ;
           impl * pimpl ;
    
    };
    
    //cpp file
    struct impl {std::string data; }
    
    void Foo::Copy( const Foo & f ) {
          pimpl->data = f.pimpl->data;
    }