NebulaFox
NebulaFox

Reputation: 8313

conversion const object reference to const object

I recently learned that

Object const & object();

Object o = object();

would cause a copy. So I am curious as to what happens when

Object const o = object();

will do.

Upvotes: 0

Views: 129

Answers (3)

Arpit
Arpit

Reputation: 12797

References are not object but they are just an alias so assigning a reference is same as assigning an object.

Object const & object();

Object o = object();   //here o is not constant. you can do o=object() again.

Object const o = object();  //here o is constant. you can't do o=object() again after its initialization.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143101

Also copy, your o should be constructed as long as it's an object. Copy-constructed here.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477060

It'll also make a copy.

To avoid a copy, you can create a reference that is bound to the same object as the reference that the function returns:

Object const & o = object();

Upvotes: 1

Related Questions