Girardi Girardi - 3 months ago 9
C++ Question

Is it needed to delete a pointer that is not instantiated to a variable?

I have a

Base
class, with two derived classes
DerivedA
and
DerivedB
and a factory method that returns a pointer
Base*
.

Base* GetClass(int choice)
{
if (choice == 0)
return new DerivedA();
else if (choice == 1)
return new DerivedB();
throw std::invalid_argument("no no no");
}


Both
DerivedA
and
DerivedB
implement a method, say
GetDouble()
, and this method is the only thing that interests me about constructing either of these classes:

double d = GetClass(0)->GetDouble();


My question is: when I call GetClass(0) I create a pointer that should be deleted. However, I am not instantiating it to an object. Should I still need to delete it?

Something like:

Base* c = GetClass(0);
double d = c->GetDouble();
delete c;


How would that work with
std::unique_ptr
?

Thank you in advance.

PS: I think there are related questions, like this and this, but mine is a little more specific.

Answer

By using std::unique_ptr, you wouldn't have the trouble of calling delete.

std::unique_ptr<Base> GetClass(int choice)
{
    if (choice == 0)
        return std::make_unique<DerivedA>();
    else if (choice == 1)
        return std::make_unique<DerivedB>();
    throw std::invalid_argument("no no no");
}

And you can now safely call:

double d = GetClass(0)->GetDouble();

What happens here is that: GetClass(0) will return an rvalue that will only be destroyed at the ;. Hence, chained calls such as GetClass(0)->func->func->etc(); will still have the object returned by GetClass() alive until ;

Remember ; is one of C++'s most powerful feature.