Motivation: I have two objects, A
and B
. I know that A
has to be instantiated before B
, maybe because B
needs information calculated by A
. Yet, I want to destruct A
before B
. Maybe I am writing an integration test, and I want server A to shut-down first. How do I accomplish that?
A a{};
B b{a.port()};
// delete A, how?
Solution: Don't allocate A
on the stack. Instead, use std::make_unique
and keep a stack-allocated smart pointer to a heap-allocated instance of A
. That way is the least messy option, IMO.
auto a = std::make_unique<A>();
B b{a->port()};
// ...
a.reset()
Alternatively, I considered moving the destruction logic out of A
's destructor and calling that method explicitly myself. The destructor would then call it only if it has not been called previously.