Re: Design question related to std::auto_ptr
* Vladimir Jovic:
Alf P. Steinbach wrote:
* Vladimir Jovic:
abhay.burli@gmail.com wrote:
Hello Group,
Consider the following class design using forward declarations.
//start-snip
#include<memory>
class Details;
class MyConcrete {
private:
std::auto_ptr<Details> details_;
};
int main() {
MyConcrete obj;
return 0;
}
// end-snip
[more sniping]
From this example, to me it looks like the OP wanted to implement the
pimpl
Q-2. Do boost smart-pointers also have the same semantics w.r.t to the
above situation?
Off course
Happily that's incorrect. :-)
std::auto_ptr's referent type is required to be complete, but that is
not a requirement of e.g. boost::shared_ptr.
And in particular, boost::shared_ptr provides custom deleter
functionality that probably can handle the OP's case with ease
(weasel-words present because the example is lacking in detail).
I am bit confused. Don't you need the class declaration to use that
class? (assuming the class is defined somewhere ;) )
Do you have an example where you would only forward declare a class, and
then do something useful with it?
Well, the PIMPL idiom is a/the prime example of taking advantage of this
property -- or lack of requirement -- of boost::shared_ptr.
For the PIMPL idiom it's not even necessary to explicitly use a custom deleter
because with PIMPL you can easily arrange to have a complete referent type at
the time of initialization of the shared_ptr. And shared_ptr then just does The
Right Thing. It generates a deleter function that it calls on destruction.
I.e., in the implementation file it goes like this:
class Foo::Impl {}; // Complete definition of Impl class.
Foo::Foo()
: myPImpl( new Impl ) // shared_ptr has all info it needs here.
{}
Some folks have argued that the same technique must in practice have to work
nicely also for std::auto_ptr, at least if also Foo::~Foo() is defined in the
implementation file, because how could any compiler manage to screw up things
then? But according to the standard's general rules it's just UB to do it with
std::auto_ptr. And one risks the compiler warning about that UB, as above.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!