Reputation: 387
Can the code below cause segmentation fault?
struct Dim {
int x, y, z;
};
Dim set_dim(int a) {
Dim l;
l.x=a;
l.y=a;
l.z=a;
return l;
}
int sum(const Dim &m) {
int s=m.x+m.y;
return s;
}
main() {
cout<<sum(set_dim(5))<<endl;
}
I think it can because a reference is taken of a local variable 'l' in set_dim, in other word a reference to variable now out of scope. But never the less it works
Upvotes: 1
Views: 145
Reputation: 5998
A reference of l
is never taken (not directly may be due to return value optimizations indirectly but you don't have to worry about that).
set_dim
returns a copy of l
. A temporary copy which will be
passed to sum
.
sum
can accept a temporary because it takes a const reference and
everything worked out just fine and they all lived happily until
sum
returned.
Upvotes: 3
Reputation: 519
set_dim
does not return a reference but a copy of l, so I don't think there is any chance of seg fault.
Upvotes: 1
Reputation: 110748
This is well-defined. set_dim
returns by value, so its returned object is a temporary copy of the local variable l
. This temporary is then bound to the const
reference argument of sum
. This affects the lifetime of the temporary object:
A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
So the lifetime of the temporary object is the full-expression cout<<sum(set_dim(5))<<endl;
. It still exists while sum
is executing.
Upvotes: 3