Other issues aside (copy constructor, ec.), if you want to access impl::data
without imposing the <string>
header to all your clients, you can do something like the following:
// 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;
This is a hack-ish work-around for having a std::string Foo::data() const
member function. The idea is that you can have the <string>
header included by only the clients who need it.
Disclaimer: I really don't like this approach. It's very inelegant and is unlikely to really increase compile times. Some compilers cache (or pre-compile) standard library headers so as to help people avoid this kind of mess.