Background
With normal pointers, I can do something like the following
void conditional_reassign(MyClass* ptr)
{
if (my_condition)
{
delete ptr;
ptr = new MyClass(new_param);
}
}
And I can pass in the pointer I want to change like following
MyClass* ptr = new MyClass(old_param);
conditional_reassign(ptr);
I wish to reimplement this with std::unique_ptr
. Here's what I came up with
std::unique_ptr<MyClass> conditional_reassign2(std::unique_ptr<MyClass> ptr)
{
if (my_condition)
{
ptr = std::make_unique<MyClass>(new_param);
}
return std::move(ptr);
}
And I would call it with the following
std::unique_ptr<MyClass> ptr = make_unique<MyClass>(old_param);
ptr = std::move(conditional_reassign2(std::move(ptr)));
Question
I'm not quite happy with the verbosity of the line
ptr = conditional_reassign2(std::move(ptr));
Is there a way to implement conditional_reassign2
so that I can call it in a manner similar to conditional_reassign(ptr)
Edit
I should note a major issue with
ptr = std::move(conditional_reassign2(std::move(ptr)));
is that it will destroy the original object ptr
pointed to regardless of my_condition
(see Why does reassigning a smart pointer to itself cause destruction?)