I'd like to enforce that an object should exist before passing it to a function:
void Class::setStoredObject(MustExist& obj) {
stored_object = &obj;
}
// Lifetime of ptr is my responsibility
std::unique_ptr<MustExist> ptr = std::make_unique<MustExist>();
classObject.setStoredObject(*ptr);
anyway I also need to store that object (big one) by reference or address so I usually grab a pointer to it.
Is this safe to do? I.e. getting the address of a reference to refer to the original pointed-to object.
Alternatively, any other/better way that I could achieve this?
There's nothing wrong with this, per se. Of course, if the original object goes out of scope and gets destroyed, the saved pointer to the object will no longer be valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With