I have a question about C++ references, I'm wondering why the following code is invalid:
class NonCopyable {
public:
NonCopyable() = default;
NonCopyable(const NonCopyable &) = delete;
NonCopyable &operator=(const NonCopyable &) = delete;
};
class RefOwner {
public:
RefOwner(NonCopyable &ref) : ref_(ref) {}
void assign(NonCopyable &ref) { ref_ = ref; } // <- error: use of deleted function ‘NonCopyable& NonCopyable::operator=(const NonCopyable&)’
protected:
NonCopyable &ref_;
};
I was expecting that only the reference to the object (so an address) should be copied, not the whole object, so it should be valid.
The same code using a pointer works just fine:
class RefOwner {
public:
RefOwner(NonCopyable &ref) : ref_(&ref) {}
void assign(NonCopyable &ref) { ref_ = &ref; } // ok
protected:
NonCopyable *ref_;
};
I expected these 2 examples to have the same behaviour, but the first one is invalid. Why is that ?
Thanks for your answers.