In C++17 Qt5.15, I have a QHash of <int, std::unique_ptr<MyClass>>, how do I get the…
- User
In C++17 Qt5.15, I have a QHash of <int, std::unique_ptr>, how do I get the value as a reference? operator[] tries to return a copy of the value which obviously breaks the build
- Assistant
Great question! In Qt5.15 with C++17, if you have a
QHash<int, std::unique_ptr<MyClass>>, you cannot useoperator[]to get a reference to thestd::unique_ptr<MyClass>value directly, becauseQHash::operator[]returns a copy of the value (not a reference), which is not allowed forstd::unique_ptr(non-copyable).Why does this happen?
QHash::operator[]is designed to return a value (by value), not a reference.std::unique_ptris move-only and non-copyable.- So,
QHash::operator[]will not compile withstd::unique_ptras the value type.
How to get a reference to the value?
You need to use iterators to access the value by reference.
Example
QHash<int, std::unique_ptr<MyClass>> hash; // Insert an element hash.insert(42, std::make_unique<MyClass>()); // Find the element auto it = hash.find(42); if (it != hash.end()) { // it is a QHash<int, std::unique_ptr<MyClass>>::iterator std::unique_ptr<MyClass>& ptr = it.value(); // Reference to the unique_ptr MyClass* obj = ptr.get(); // Raw pointer to MyClass // Now you can use obj or ptr as needed }Notes
it.value()returns a reference to the value (std::unique_ptr<MyClass>&).- You can safely modify or move the unique_ptr via this reference.
Summary Table
Access method Returns Works with unique_ptr? hash[42]Value (by copy) ❌ (does not compile) hash.find(42)Iterator ✅ it.value()Reference to value ✅
Alternative: Use
std::unordered_mapIf you use
std::unordered_mapinstead ofQHash, itsoperator[]returns a reference to the value, so it works withstd::unique_ptr:std::unordered_map<int, std::unique_ptr<MyClass>> map; map[42] = std::make_unique<MyClass>(); std::unique_ptr<MyClass>& ptr = map[42]; // OK!
Conclusion
With
QHash<int, std::unique_ptr<MyClass>>, always usefind()andit.value()to get a reference to the value.
operator[]will not work due to the copy requirement.If you need
operator[]-style access, consider usingstd::unordered_mapinstead. - User
okay, constfind sound like the best bet, how do I idiomatically return the raw (non-owning) pointer / nullptr if not found? This is probably not safe, right? return hash.constFind(id).value().get();
- Assistant
Great follow-up! You're right to be cautious:
return hash.constFind(id).value().get();
is not safe if the key is not found, becauseconstFind()returnshash.constEnd()when the key is missing, and calling.value()on that is undefined behavior.
Idiomatic and Safe Way
You should check if the iterator is valid before accessing
.value():const auto it = hash.constFind(id); if (it != hash.constEnd()) { return it.value().get(); // returns MyClass* (raw pointer) } else { return nullptr; }Or, as a one-liner (C++17):
const auto it = hash.constFind(id); return (it != hash.constEnd()) ? it.value().get() : nullptr;
Wrap in a Function
Here's how you might write a helper function:
MyClass* getRawPtr(const QHash<int, std::unique_ptr<MyClass>>& hash, int id) { const auto it = hash.constFind(id); return (it != hash.constEnd()) ? it.value().get() : nullptr; }
Safety
- This is safe: you only access
.value()if the iterator is valid. - The returned pointer is non-owning and only valid as long as the
QHashand the corresponding entry exist.
Summary
- Never call
.value()onconstEnd(). - Always check
it != hash.constEnd()before accessing.value(). - Returning a raw pointer is fine as long as you document that it's non-owning and may become invalid if the hash is modified.
Let me know if you want a version for
std::unordered_mapor more details! - This is safe: you only access
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.