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
}
C static code analysis: Conditional operators should not be nested.
In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if (abbreviated iif).
The conditional operator can be used in the case of an if-else statement if the if-else statement only has one statement to execute. The conditional operator reduces the number of lines of code in a program. The conditional operator is a single programming statement and can only perform one operation.
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.
live example on godbolt.org
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With