I read C++: auto_ptr + forward declaration? and its answers, especially the accepted one and I'm aware of the pitfalls when combining auto_ptr and forward declarated classes. But I'm encountering runtime problems with this same pattern that seems not to be covered by this Q&A (and all other auto_ptr-tagged Questions I checked).
When destroying my Outer
-like class[1], I sometimes get an access violation, sometimes I only observe missing destructor calls.
// Outer.h - an example header
#include <uncopyable.h>
#include <memory>
class Inner;
class Outer: private Uncopyable
{
public:
Outer()
~Outer();
private:
std::auto_ptr<Inner> inner;
};
I'm implementing constructor and destructor in the cpp file and there the definition of the Inner
type is present.
// Outer.cpp - an example implementation
#include "Outer.h" //< I use this include order to ensure compileability
#include "Inner.h" //< for units including Outer.h without preconditions
Outer::Outer(): inner(new Inner) {}
Outer::~Outer() {}
The described problems disappear if I:
- include
Inner.h
withinOuter.h
or - explicitly calling
inner.reset()
I work on legacy code that compiles only with C++-Builder 6, so I've to stick to std::auto_ptr
since it's the only smart_ptr implementation the compiler seems to support, so there is (currently) no alternative to this type (that I know is deprecated by C++11).
My question: What am I doing wrong here, or is it maybe a well-known bug in BCB6[2]?
Additional Remark I expected that using auto_ptr on uncomplete types would be safe having read Herb Sutter's article Using auto_ptr Effectively, the section Wrapping Pointer Data Members deals with it. The problems I describe above are therefore a very confusing experience.
- [1] This example is cut down to discuss the formal structure of auto_ptr usage.
- [2] Borland C++ 5.6.4, and the STL shipped with C++-Builder 6 (upd4)