Adrian17
Adrian17

Reputation: 443

Why does referencing an unique_ptr behave this way?

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.

Upvotes: 3

Views: 87

Answers (3)

Initialising a reference is very different from assigning to it. When you initialise a reference, you set it to refer to an object. Everywhere thereafter, using the reference actually means using the referred object. This means that assigning to the "reference" actually means assigning to the referred-to object.

And in your case, the assignment is illegal, because std::unique_ptr cannot be copied (so, by extension, neither can a vector of them, of course).

Upvotes: 0

avakar
avakar

Reputation: 32685

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

Upvotes: 6

juanchopanza
juanchopanza

Reputation: 227608

The problem is that you are assigning vec1 to vec2, and this cannot be done because the contents of the vectors are not assignable.

This

otherReference=vec2; 

is exactly the same as

vec1 = vec2;

because otherReference is an alias for vec1. Wherever you see otherReference in an expression, you can replace it by vec1.

Upvotes: 4

Related Questions