Reputation: 3823
I would like to understand what happens in the following code
struct A
{
vector<double> x;
};
void f(A &a)
{
vector<double> &y = a.x;
}
When the function f exits, is a.x destroyed? Thanks in advance!
Upvotes: 1
Views: 1070
Reputation: 336
In this case, when you enter f()
you locally create a reference y
to a.x
that exists independently from a
and the rest of the world. When you leave f()
the locally created reference y
goes out of scope and gets destroyed. The rest of the world stays as it was before you entered f()
.
Upvotes: 3
Reputation: 476930
Remember that references are not objects. y
is a variable, but not an object. It is a reference to the existing object a.x
, but that object itself is not local to the scope of f
. So the variable y
goes out of scope at the end of f
, but the object to which it refers does not.
Upvotes: 4
Reputation: 21351
No a.x
is not destroyed. You simply have created a local reference to a.x
and then the function exits - nothing is changed. Your code effectively does nothing at all.
Upvotes: 4