How do you exchange personal data with Pimpl without exposing the inside?

If you have an object B that needs a copy of the private member of object A and the private member is hidden by Pimpl, how do you do this without exposing the 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.
+3
source share
3 answers
// 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;
}
+7
source

Fooyou must implement the constructor, copy constructor, destructor and assignment operator, doing the "right thing" - letting you do, for example. 'A = B;'

// Foo.h
struct FooImpl;
class Foo
{
  Foo(Foo const &);
  Foo();
  ~Foo();
  Foo & operator=(Foo const & RHS);
private:
  FooImpl * pimpl;
};

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

Foo & Foo::operator=(Foo const & RHS) {
  *pimpl = *RHS.pimpl;
  return *this;
}
Foo::Foo(Foo const & V) {
  pimpl = new FooImpl(*V.pimpl);
}

Foo::Foo() {
  pimpl = new FooImpl;
}

Foo::~Foo() {
  delete pimpl;
}

Now you can safely:

Foo A;
Foo B;
A = B;
+3
source

( , ec.), impl::data <string> , - :

// Foo.h
class FooUtil;
class Foo
{
friend class FooUtil;
private :
  struct impl ;
  impl * pimpl ;
};

// FooUtil.h
#include <string>
class FooUtil
{
public:
    static std::string data_of(const Foo&);
};

// Foo.cpp
struct impl { std::string data; }
std::string FooUtil::data_of(const Foo& foo)
{
    return foo.impl->data;
}

//main.cpp
Foo A;
Foo B;

hack-ish work-around std::string Foo::data() const. , <string> , .

Disclaimer . I really don't like this approach. This is very inelegant and is unlikely to really increase compilation time. Some compilers cache (or precompile) standard library headers to help people avoid this kind of mess.

0
source

All Articles