Lets say I have a polymorphic class Structure like that
class Base
{
//some implementation
};
class Deriv: public Base
{
//implementation
}
class Case1
{
boost::scoped_ptr<A> a_ //polymorphic data member owned by C
public:
Case1(A* a):a_(a)
{
}
};
class Case2
{
boost::scoped_ptr<A> a_ //polymorphic data member owned by C
public:
Case2(std::auto_ptr<A> a):a_( a.release() )
{
}
};
And I’ve got a third class case1/2 which owns one of those polymorphic object described above. Now I need to pass a pointer to a Base/Deriv object to the constructor of the case1/2 class which takes ownership of this object. Should I pass this object as a smart pointer e.g. auto_ptr to make it clear I’m takin care of this object, or allow raw pointers( case 1 ) to allow a much simpler syntax like
Case1 c(new Deriv);
//compared to
Case2 c(std::auto_ptr<Base>(new Deriv));
You need to pass a smart pointer and you need to name that smart pointer (e.g., it can’t be a temporary):
In your first example,
Case1 c(new Deriv);, the object could be leaked if an exception is thrown between whennew Derivis executed and when theCase1object takes ownership of it in its constructor.In your second example, where you don’t name the smart pointer, the object could be leaked in some circumstances. Notably, this can happen if you have more than one argument to a function.