Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-2025-04-14· OpenAIHugging Face LMArena Human Preference 140K

In C++17 Qt5.15, I have a QHash of <int, std::unique_ptr<MyClass>>, how do I get the…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-03-26-experimental’s answer.
  1. 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

  2. Assistant

    Great question! In Qt5.15 with C++17, if you have a QHash<int, std::unique_ptr<MyClass>>, you cannot use operator[] to get a reference to the std::unique_ptr<MyClass> value directly, because QHash::operator[] returns a copy of the value (not a reference), which is not allowed for std::unique_ptr (non-copyable).

    Why does this happen?

    • QHash::operator[] is designed to return a value (by value), not a reference.
    • std::unique_ptr is move-only and non-copyable.
    • So, QHash::operator[] will not compile with std::unique_ptr as 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 methodReturnsWorks with unique_ptr?
    hash[42]Value (by copy)❌ (does not compile)
    hash.find(42)Iterator✅
    it.value()Reference to value✅

    Alternative: Use std::unordered_map

    If you use std::unordered_map instead of QHash, its operator[] returns a reference to the value, so it works with std::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 use find() and it.value() to get a reference to the value.
    operator[] will not work due to the copy requirement.

    If you need operator[]-style access, consider using std::unordered_map instead.

  3. 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();

  4. 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, because constFind() returns hash.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 QHash and the corresponding entry exist.

    Summary

    • Never call .value() on constEnd().
    • 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_map or more details!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.