Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting address of object pointed by reference

Tags:

c++

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?

like image 619
Dean Avatar asked Dec 16 '25 16:12

Dean


1 Answers

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.

like image 92
Sam Varshavchik Avatar answered Dec 19 '25 07:12

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!