I have three classes in my example. Foo, FooRepository and FooImpl.
Foo is a lightweight wrapper around FooImpl. The idea is that Foo
can be used to pass elements by value from FooRepository to the
client code.
One option would be to use shared_ptr, but this seems like overkill
for my particular situation. The client will not be storing or
copying the Foo objects, so I have chosen to implement Foo in the
following way:
class Foo {
public:
Foo(FooImpl* impl) : pimpl_(impl) {}
//A few functions follow that simply forward requests
//...
private:
auto_ptr<FooImpl> pimpl_;
};
FooRepository returns Foo objects by value. The signature is:
class FooRepository {
public:
Foo getFoo();
};
And the client code does the following:
Foo foo = aFooRepository.getFoo();
The idea is that the foo object created here has ownership of the
FooImpl and when it goes out of scope, the FooImpl is automatically
deleted. Resource leaks are also handled in case the return value
is ignored.
This works great on Forte compilers, but fails on GCC with the
error message:
Foo.cpp: In function `int main(int, char**)':
Foo.cpp:25: error: no matching function for call to `Foo::
Foo(Foo)'
Foo.h:16: error: candidates are:
Foo::Foo(Foo&)
Foo.h:18: error:
Foo::Foo(FooImpl*)
It appears that the presence of the auto_ptr in the Foo class
prevents the compiler from generating the copy constructor taking a
const-ref parameter, and the client code matching the function call
properly.
The error message makes no sense to me because the copy constructor
cannot be written to take a parameter by value.
What is the best way to handle this situation? Am I missing
something obvious? I realize that the tradeoff I made here was to
simplify memory management but gave up the possibility of storing
my Foo objects inside containers. Is there a standard pattern for
this type of object management?