In the following code snippet, are there any caveats that need to be considered?
void do_stuff()
{
std::unique_ptr<my_type> my(new my());
my_type& mine = *my;
//use mine
}
It gives me a weird feeling to ‘bring out’ the value of my by dereferencing the implicit pointer, as it feels like it would create a temporary (but I’m quite sure that’s not the case)
The code is fine with the usual caveats when holding a reference (or pointer) to an object: you have to make sure that the object outlives the uses of the pointer or reference.
In this particular case, make sure that the object inside the
unique_ptrdoes not get deleted by a call toreset()ordelete my.release();which I think are the only cases where the lifetime of that reference might outlive the lifetime of the object itself.Side note: I am assuming that you have a good reason to use dynamic allocation for that object. If you are not sure, consider not using pointers/new in the first place.
I am also assuming that the reference is not there for performance, if it is, you might want to consider as access through the reference or the smart pointer will be translated to exactly the same binary.