Re: initializing std::auto_ptr variable in class constructor - how
to dow this?
XP wrote:
I was wondering if this is possible. As I currently use something like this:
class Ta {
public: Type * pType;
Ta();
~Ta();
}
// Constructor - initialize pType
Ta::Ta() {
pType = new Type();
}
// destroy pType
Ta::~Ta() {
delete pType;
}
So... how would you do it with std::auto_ptr so that it doesn't go out of
scope?
class Ta
{ std::auto_ptr<Type> pType;
public:
Ta() : pType(new Type()) {}
};
But note that this will make your class non-copyable.
However, scoped_ptr<> is more appropriate for this purpose.
> Or maybe I should go with boost::shared_ptr with one additional
reference that won't go out of scope.
? - what is the meaning of 'additional reference'?
Furthermore the use of shared_ptr, as the name suggests, will result in
copies of Ta that share the same instance of Type (unless you force
something else by an explicit implementation of copy constructor and
assignment operator). This might not be intended.
I could place std::auto_ptr<Type>
pType(new Type()); but that would of course go out of scope as soon as
constructor has finished. Any way to force it to stay defined until
destructor?
Yes, see above.
It will not go out of scope until the auto_ptr goes out of scope. And
this is exactly after the destructor of Ta.
Marcel