Prev: Is it valid to assign a reference from a ternary expression (i.e. operator ?:)
Next: template class with template member function in cpp file
From: kathir on 3 Jun 2010 14:30 On Jun 3, 12:54 pm, 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 { quoted banner removed; please do it yourself. -mod } Assigning a reference through ternary expression is fine. The following code would work...! int objA = 10; int objB = 20; bool flag = 0; int& objRef1 = (flag == 1) ? objA : objB; int& objRef2 = (flag == 0) ? objA : objB; Regards, Kathir http://www.softwareandfinance.com -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |