Why does referencing an unique_ptr behave this way?

c++, reference, unique-ptr

Solution

This has nothing to do with references, it's the `unique_ptr` that cannot be copied.

unique_ptr<int> p1, p2;
p1 = p2; // error

Consequently, vectors of `unique_ptr` cannot be copied either.

vector<unique_ptr<int>> vec1, vec2;
vec1 = vec2; // error

Problem

``` vector<int> v1, v2; /*1*/ vector<int> &someReference=v1; //compiles /*2*/ someReference=v2; //compiles vector<unique_ptr<int>> vec1, vec2; /*3*/ vector<unique_ptr<int>> &otherReference=vec1; //compiles /*4*/ otherReference=vec2; //ERROR ``` I would understand if neither line 3 nor 4 didn't compile, but the third one doesn't cause any compilation errors - apparently there are no problems with initializing the reference for the first time and passing it around; the problem only appears when I try to assign it the second time. I can't understand what is going on behind the scenes that makes the second assignment impossible.

Original source