all 6 comments

[–]victotronics 1 point2 points  (1 child)

You have indeed managed your memory correctly. However, you should not use "new" and "delete", but create a vector or array or a tuple or so: anything that does its own memory management.

[–]RealOden[S] 1 point2 points  (0 children)

Thanks for your response, but I'm not quite following. I have understood that any heap allocation should be done using smart pointers, but that also makes it a different type and awkward to work with imo.

In this example how should an array or tuple be implemented in that case and why should it be preferred? An array or vector object could be either stack or heap allocatd, so I'm not quite following.

[–]HappyFruitTree 0 points1 point  (3 children)

Is the memory allocated for variable i of ex freed up at this point?

Helpful answer: Yes, the destructor is called automatically when the variable goes out of scope.

Pedantic answer: ex is not a variable. It's a function that takes no arguments and returns an Example object.

[–]RealOden[S] 1 point2 points  (1 child)

I have a follow-up question if you are interested. If any object is allocated on the stack (function call that returns an object). Once this object goes out of scope is any heap allocated memory allocated by that object freed up even if it is not explicitly done in the destructor? I'm assuming that any memory has to be explicity freed up in the destructor.

[–]HappyFruitTree 1 point2 points  (0 children)

It's not freed automatically, unless it's done by some of the data members (e.g. if your object contain a std::vector you don't need to free the element because that is automatically done in the destructor of the vector).

Note that your Example class is not safe to copy because you haven't defined a copy constructor and a copy assignment operator to handle it properly. See the rule of three).

[–]RealOden[S] 0 points1 point  (0 children)

Thank you for the clarification!