Reputation: 370
could someone explain me why c
and c1
are constructed different way.
I understand that I have reference to copy created by '?' operator, which is destroyed after construction, but why in first case it behave other way.
I've tested if its optimization, but even with conditions read from console, I have same result. Thanks in advance
#include <vector>
class foo {
public:
foo(const std::vector<int>& var) :var{ var } {};
const std::vector<int> & var;
};
std::vector<int> f(){
std::vector<int> x{ 1,2,3,4,5 };
return x;
};
int main(){
std::vector<int> x1{ 1,2,3,4,5 ,7 };
std::vector<int> x2{ 1,2,3,4,5 ,6 };
foo c{ true ? x2 : x1 }; //c.var has expected values
foo c1{ true ? x2 : f() }; //c.var empty
foo c2{ false ? x2 : f() }; //c.var empty
foo c3{ x2 }; //c.var has expected values
}
Upvotes: 12
Views: 944
Reputation: 93274
The type of a conditional expression is the common type of the two branches, and its value category also depends on them.
For true ? x2 : x1
, the common type is std::vector<int>
and the value category is lvalue. This can be tested with:
static_assert(std::is_same_v<decltype((true ? x2 : x1)), std::vector<int>&>);
For true ? x2 : f()
, the common type is std::vector<int>
, and the value category is prvalue. This can be tested with:
static_assert(std::is_same_v<decltype((true ? x2 : f())), std::vector<int>>);
Therefore you are storing a dangling reference in c1
. Any access to c1.var
is undefined behavior.
Upvotes: 21