Prev: Access method names for std::random
Next: Is it valid to assign a reference from a ternary expression (i.e. operator ?:)
From: JoeO on 3 Jun 2010 04:54 I've got old code which attempts to assign a reference to an object from the results of a ?: ternary expression. Is this valid? To illustrate class T {}; void Foo() { T objA; T objB; T& objRef = (boolean expression) ? objA : objB; (do something with 'objRef') } Of course 'objRef' is supposed to refer to one of the original object, not some rvalue copy. I've got old code which does this and works but it might be due to a bug in the compiler's handling of ?: . A bug which I know has now been fixed in the latest version. According to the 2003 standard regarding operator ?: , (5.16 paragraph 6) "If the operands have class type, the result is an rvalue temporary of the result type, which is copy-initialized from either the second operand or the third operand depending on the value of the first operand. " If I understand correctly, the operands in my example DO have class type (and not... well... "reference" type). So objRef should NOT refer to the original objects but rather to a temporary. Am I correct? If so, I must change the code.. Would it be valid to do this? T* pObj = (boolean expression) ? &objA : &objB; Thanks. -Joe -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |