简体   繁体   中英

Unique Pointers: LValue Reference vs RValue Reference function calls

I started using c++ std::unique_ptr s and I stumbled across the following problem:

I want to pass a reference of my unique pointer to a function and assign a new value to the pointer in this function. Intuitively, I think the function needs to take a lvalue reference to be able to modify the pointer. But, in the following code example both options ( lvalue reference and rvalue reference + std::move ) do the same thing (I suppose).

#include <memory>
#include <utility>

struct Widget {
    Widget(int) {}
};

void reseat_RValue(std::unique_ptr<Widget>&& uniqPtr) {
    auto tempUniqPtr = std::make_unique<Widget>(2003);
    uniqPtr = std::move(tempUniqPtr);
}

void reseat_LValue(std::unique_ptr<Widget>& uniqPtr) {
    auto tempUniqPtr = std::make_unique<Widget>(2010);
    uniqPtr = std::move(tempUniqPtr);
}

int main() {
    auto uniqPtr = std::make_unique<Widget>(1998);

    reseat_RValue(std::move(uniqPtr)); // (1)

    reseat_LValue(uniqPtr); // (2)   
}

I don't really understand, what's the difference between (1) and (2) or rather which one I should use for my use-case. So maybe someone could explain what is going on with each of this functions and which one I should use.

Yes they do the same thing. From your intent, ie passing-by-reference and modifying it in the function, passing-by-lvalue-reference would be better. It makes your intent more clear (as @bitmask suggested); the function expects an lvalue and would modify it inside the function. And for passing-by-rvalue-reference you need to use std::move for lvalues to be passed to the function, and it allows to pass rvalues like temporaries which seems meaningless. eg

// meaningless; the temporary `std::unique_ptr` would be destroyed immediately
reseat_RValue(std::make_unique<Widget>(1998)); 

Actually std::unique_ptr::reset does the same thing for you in function with lvalue reference - it is simpler. IMO, the rvalue semantics fits best for huge objects, not for pointers. But yes, unique_ptr uses it to achieve a sole pointer count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM