Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional ? : operator with class constructor

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
}
like image 406
geniculata Avatar asked Nov 23 '18 14:11

geniculata


People also ask

Can conditional operator be nested?

C static code analysis: Conditional operators should not be nested.

Which operator is used to construct conditional?

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).

Can we use conditional operator?

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.


1 Answers

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

like image 111
Vittorio Romeo Avatar answered Sep 20 '22 12:09

Vittorio Romeo