Possible scenarios to justify heap-allocated variables scoped locally?
Solution 1:
First of all there is no reason to not use a smart pointer here, i.e.
auto a = std::make_unique<A>(/* arguments */);
but as to why you would want to heap allocate rather than creating the object on the stack, reasons include
- Size. Class A might be huge. Stack space is not inexhaustible; heap space is much much larger. Seriously, you can overflow the stack surprisingly easily, even on modern machines. You don't want to stack allocate an array of 100,000 items, etc.
- You might need a pointer for runtime polymorphism. Say instead of calling A's constructor directly you are calling some factory function that returns a unique_ptr to a base class from which A inherits and the rest of your code depends on polymorphic calls to
a
; you'd need to use dynamic allocation in that case.