I don't believe you can do this directly with the shared_ptr API.
If Lib::SomeClass is an interface/abstract base class, you might be able to use a Decorator. The idea would be to define a class which subclasses Lib::SomeClass
, contains a shared_ptr<Lib::SomeClass>
and a std::ofstream*
, and whose methods all forward to the corresponding method of the contained shared_ptr. The decorator's destructor, however, would delete the contained ofstream
(or you could store it in some sort of RAII container like a scoped_ptr
). So it would be an instance of the Decorator that you passed to appendWriter. Here's a sketch:
class SomeClassDecorator : public Lib::SomeClass
{
public:
SomeClassDecorator(shared_ptr<Lib::SomeClass> p, std::ofstream* stream)
: p_(p), stream_(stream)
{}
virtual int MethodOfSomeClass(int x) {
return p_->MethodOfSomeClass(x);
}
private:
shared_ptr<Lib::SomeClass> p_;
scoped_ptr<std::ofstream> stream_;
};
std::ofstream* out = new std::ofstream();
...
shared_ptr<Lib::SomeClass> writer = Library.createWriter(out);
shared_ptr<Lib::SomeClass> wrapper(new SomeClassDecorator(writer, out));
Library.appendWriter(wrapper);