Prev: template class with template member function in cpp file
Next: Aggregate initializers of static objects
From: mingze zhang on 3 Jun 2010 23:34 On Jun 4, 3:54 am, JoeO <joseph.m.ole...(a)gmail.com> wrote: > 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 > To further clear your doubt, you shall note that in the standard, (5.16 paragraph 6) is only applied when paragraph 1-5 are failed! You shall read 1-5 carefully and you'll find that the example you mentioned deserves an lvalue result! Note that for those cases the results are rvalues (prvalues), the standard does mention them. So you shall assume that when the result is not mentioned, it will be lvalue! Normally we only use this case, if both operands are of the same type (or implicitly convertible) and are lvalues, the result is an lvalue. so you can not only use it to initialize reference, but also do this, (a == 0) ? b : c = 3; -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |