I have a user defined class that has a std::unique_ptr
member. I am trying to overload the assignment operator to new an object of the same type to the unique_ptr
member or assign the value to the ptr
value.
class object
{
public:
// POD types
object& operator=(const object& _obj);
std::unique_ptr<baseClass> ptr;
}
I've tried using:
std::unique_ptr::swap()
but the swap function is non-const so I attempted assigning the the result of:
std::unique_ptr::get()
to the ptr
and then calling:
std::unique_ptr::release()
but release also is non const, so I cannot guarantee that ptr
will be destructed correctly since the old ptr
will still have ownership. Alas, operator=()
for unique_ptr
does not accept a non-const reference to another unique_ptr
so I have opted to make the operator= as so for my class.
object& object::operator=(const object& _obj)
{
//POD types use operator= as normal
ptr.reset(nullptr);
return *this;
}
And just call a setPtr()
method later on to set the ptr
. I wanted to just detect the type and just assign the ptr
using:
ptr.reset(new detectedType );
but the consensus all over Stack Overflow and my preferred search engine is that detecting types like this would be a design flaw. My question is: am I overlooking something simple and is there a better way to overload the assignment operator for user defined types that have a unique_ptr
member?
Before post edit:
I changed the parameter to object&
rather than const object&
and it worked. Is this a good way to correct this issue or should I be trying to work with only const references to the other class?