Max
Max

Reputation: 4405

Dereferencing a pointer into a reference in c++

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)

Upvotes: 1

Views: 1290

Answers (3)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

Make sure that the pointer outlives the (use of the) reference.

One simple way to do that is to use const:

void doStuff()
{
    auto const p    = std::unique_ptr<MyType>( new MyType );
    MyType&    m    = *p;

    // use m
}

Of course, if there is not any special reason to prefer dynamic allocation (such as size, or special allocator) then just use automatic allocation for the MyType object, i.e. declare it directly as a local variable without using the word static.

Upvotes: 0

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_ptr does not get deleted by a call to reset() or delete 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.

Upvotes: 3

pmr
pmr

Reputation: 59841

Besides not making much sense (at least in the snippet) the code is alright, if there is really nothing between the construction of my and the assignment to the reference.

Upvotes: 0

Related Questions