I am trying to understand the differences in the behavior of std::move
and the transfer of ownership with std::unique_ptr
when used with functions F1
and F2
. The code is given below:
void F1(std::unique_ptr<Dog>&& uPtr)
{
std::cout << "F1 \n";
}
void test1()
{
std::unique_ptr<Dog> pD(new Dog("Gunner"));
F1(std::move(pD));
if (pD == nullptr)
{
std::cout << "Null\n";
}
std::cout << "Test \n";
}
void F2(std::unique_ptr<Dog> uPtr)
{
std::cout << "F2 \n";
}
void test2()
{
std::unique_ptr<Dog> pD(new Dog("Smokey"));
F2(std::move(pD));
if (pD == nullptr)
{
std::cout << "Null\n";
}
std::cout << "Test \n";
}
When std::move(pD)
is used to pass pD
to F1
in test1
, pD
is not null after the call. However, when std::move(pD)
is used to pass pD
to F2
in test2
, pD
is null after the call. Why is this behavior different?