Can you have a pointer to a QHash (or other implicitly shared types)?
-
Issue:
I have two (2) QHashes in a function. I want to use a pointer to only one of them when the function is called. This block of code conceptually sums up what I'd like to do:
@
QHash<int, int> *hashptr;
QHash<int, int> firstQHash;
QHash<int, int> secondQHash;
hashptr = (goodOrBad) ? &firstQHash : &secondQHash;
do {
lots of stuff;
with whatever hash;
I happen to be pointing at;
} while(thingsAreGood);
@The problem is it doesn't work. hashptr seems to only have a subset of functionality availible to it (e.g. it compiles with "contains(key)", but I can't assign a value to it (hashptr[key] = value) . There are other ways to do what I'm after, but I'd like to understand why it doesn't work (what I'm doing wrong) so I don't keep doing the same kind of mistake.
-
Hi,
The problem you have is not a QHash but a C++ problem. In your example code, you have pointer to QHash, therefore when you use QHash, you need to dereference the pointer. Here are some examples:
@
(*hashptr)[key] = value;
hashptr->insert(key, value);
hashptr->contains(key);
(*hashptr).contains(key);
@However you can do better if you use a reference:
@
QHash<int, int> &hash = goodOrBad ? firstQHash : secondQHash;hash[key] = value;
hash.contains(key);
...
@ -
[quote author="wolf." date="1420650531"]Thank you for being so kind. I realized after posting that the problem was I wasn't dereferencing, but I'm glad I posted anyway. I wasn't familiar with using references, so I haven't been using them. It's way cleaner.
[/quote]
If you are unfamiliar with references, than I strongly suggest that you look at "this FAQ":https://isocpp.org/wiki/faq/references.
When you have some confidence with them, you could continue with "const correctness":https://isocpp.org/wiki/faq/const-correctness.