When a move happens, usually a class sets the other
's pointer to null, and this is the case with std::unique_ptr
. The assignment operator is templated so that you can move unique_ptr
s to different types (i.e derived classes).
My question is: How can it access the ptr
in the other class, a private
member, given that it's an instantiated templated class, and therefore different, and can't access private
or even protected
members?
template <typename T>
class MyPointer
{
public:
template <typename U>
void operator=(const MyPointer<U>& other) = delete;
template <typename U>
void operator=(MyPointer<U>&& other)
{
// WON'T COMPILE, THIS IS A DIFFERENT CLASS FROM THE ARGUMENT
// CANNOT ACCESS PRIVATE MEMBER
other.pointer = nullptr;
}
char* get() const { return pointer; }
private:
char* pointer;
};
int main()
{
struct B {};
struct D : B {};
std::unique_ptr<B> base;
std::unique_ptr<D> derived;
// std::unique_ptr somehow sets the other pointer to null when moving
base = std::move(derived);
MyPointer<B> my_pointer_b;
MyPointer<D> my_pointer_d;
// CANNOT ACCESS PRIVATE MEMBER
my_pointer_b = std::move(my_pointer_d);
}