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.
Aucun commentaire:
Enregistrer un commentaire