assign auto_ptr to unique_ptr
I have a function who return an auto_ptr to me and i wish to assign this pointer to a unique_ptr in my class member variable.
Code:
class Data
{
....
void Run();
private:
std::unique_ptr<Test> p_testUnique;
}
void Data::Run()
{
std::auto_ptr<Test> testPtr = GetTest();
std::unique_ptr testPtrUnique(testPtr .get());
p_testUnique = std::move(testPtrUnique);
}
Is the above correct? So now there are two pointers, testPtr and p_testUnique, both pointing to the same data returned from GetTest?
Re: assign auto_ptr to unique_ptr
I think you should use auto_ptr's release rather than get.
Re: assign auto_ptr to unique_ptr
or you could simply write
Code:
void Data::Run()
{
p_testUnique = GetTest();
}
indeed, unique_ptr has an implicit constructor from an rvalue of auto_ptr type ( that calls release() internally ); in turn, the resulting temporary unique_ptr is move assigned to your member variable.
Of course, nothing stops you from being more explicit if needed ...