Conditional ? : operator with class constructor

  • A+

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 } 


The type of a conditional expression is the common type of the two branches. For true ? x2 : x1, the common type is std::vector<int>&. For true ? x2 : f(), the common type is std::vector<int>.

Therefore you are storing a dangling reference in c1. Any access to c1.var is undefined behavior.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: