I have a not-so-ideal situation where a class returns handle references to objects that shouldn't be accessed after the parent objects' lifetimes. What is the best way to alter the pattern below to aid defensive coding?
// 'A<T>' is a thin factory-style utility class with asynchronous consumers.
template <typename T>
struct A {
A() : h_(*(new T())) { /* ... */ }
~A() { /* h_ deleted or ownership passed elsewhere */ }
// What's the best way to indicate that these handles shouldn't be used after
// the destructions of the A instances?
T &handle() { return h_; }
private
T &h_;
};
struct B { /* ... */ };
int main() {
B *b1{nullptr};
{
A<B> a;
// Is there a good way to trigger detection that the reference is bound to
// a variable which will outlive its 'valid' local lifetime?
b1 = &a.handle();
B &b2(a.handle()); // this is reasonable though
b1->ok_action();
b2.also_alright();
}
b1->uh_oh();
}
I know you can't truly prevent a user of C++ from doing most unsafe things, but if I could at least generate warnings on trivial accidental uses like this is would be the bulk of what I'd like to achieve.