On Thu, May 31, 2007 at 04:02:42PM -0400, Richard Heck wrote: > Andre Poenitz wrote: > >On Thu, May 31, 2007 at 09:12:56PM +0200, Peter Kümmel wrote: > > > >>>I tried to do something like this so I didn't have the same code in two > >>>places: > >>>QModelIndex & QCitationDialog::getSelectedIndex(QListView *) { > >>> QModelIndexList const selIdx = > >>> availableLV->selectionModel()->selectedIndexes(); > >>> if (selIdx.empty()) > >>> return QModelIndex(); //this is an invalid one. > >>> return selIdx.first(); > >>>} > >>>But that failed: warning: returns reference to temporary. Any ideas how > >>>to avoid this and still return a reference? Or could I return a smart > >>> > >>returning "const QModelIndex &" should be save. But you could also > >>return may value, copying QModelIndex isn't that expensive. The Qt > >>code return often by value, QModelIndex was designed for this. > >> > >Apart from that > > > > QModelIndex & QCitationDialog::getSelectedIndex(QListView *) { > > ... > > if (selIdx.empty()) > > return QModelIndex(); //this is an invalid one. > > > >returns a reference to a temporary, which is useless in any case > >as accessing it will invoke undefined behaviour. > > Yes, the question was how to avoid doing that and still return a > reference, if there is any such way.
If you want to use the reference outside the function (which seems desirable, otherwise one would not return it...) the 'referenced object' can't be an automatic variable (i.e. stack object) in the function as those are destroyed when the function returns. It could be something on the heap, something that got passed into the function _as reference_, some static item. However, none of these seems to be appropriate in your situation. And passing a QModelIndex is really cheap (should be around 16 bytes, with a bit luck that's just two register loads on your shiny new 64 bit machine ;-} Andre'