There was a need to use this design:

typedef QHash<int, double> Row; typedef QHash<int, Row> Matrix; 

And such a code behaves strangely:

 Matrix m; //заполняем контейнер некоторым образом int rowNumber = 1; Matrix::const_iterator it = m.constFind(rowNumber); if (it != m.constEnd()) { Row &row1 = it.value();//все хорошо работает Row &row2 = m[rowNumber];//можно поймать сегфолт } 

The Qt documentation says that even if there is no key in the hash key, when the operator [] is called, a pair will be added to the hash (key, value) where value is initialized by the default constructor. Here, the key value is guaranteed to be in the hash, but for some reason sometimes a segfolt occurs. Checked on Windows7 32bit, Ubuntu 11.10 64bit; Qt 4.7. What can you say?

  • I do not know qt, but ampersands before row1 / row2 are somewhat surprising. What would it mean? - alexlz

1 answer 1

And note that Qhash::const_iterator::value returns const T& , i.e. the element reference, and operator[] is just const T This is the whole hitch. Make your example simple with Row row1, Row row2

  • Well, actually there is also a T & operator []. But, as it seems to me now, it is selected only when used as a lvalue. It is somehow knocked out of the ideology of Qt - in all containers there is also a function const T value (const Key & key). And operator [] always gave out links. - dm_panyushkin