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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
You're correct that QHash::operator[] returns a copy of the value, which doesn't work with std::unique_ptr because it's non-copyable (only movable).
To get a reference to the std::unique_ptr<MyClass> stored in the QHash, you have two options:
1. Use QHash::value() or QHash::constFind()
Instead of operator[], use the value() method or constFind() (if you don't need to modify the value). Both return a reference (or const reference) to the stored value:
cpp
QHash<int, std::unique_ptr<MyClass>> myHash;
// populate myHash...
int key = 42;
// Non-const reference using value()
std::unique_ptr<MyClass>& ref = myHash.value(key);
// or, const reference using constFind()
auto it = myHash.constFind(key);
if (it != myHash.constEnd()) {
const std::unique_ptr<MyClass>& constRef = it.value(); // or simply *it
// use constRef
}
2. Use an iterator with QHash::find()
Alternatively, use QHash::find() to get an iterator pointing to the element. The iterator's operator*() returns a reference to the value:
cpp
auto it = myHash.find(key);
if (it != myHash.end()) {
std::unique_ptr<MyClass>& ref = *it; // dereference the iterator
// use ref
}
In both cases, you get a reference to the std::unique_ptr<MyClass> stored in the hash, without attempting to copy it.
Why value() and iterators work while operator[] doesn't:
operator[] has a dual role: if the key is present, it returns a copy of the value; if the key is not present, it inserts a default-constructed value and returns a reference to that new value. For std::unique_ptr, default construction means nullptr, but the insertion part still requires a copy (or move) operation, which isn't allowed for std::unique_ptr.
value() and iterators (find(), constFind()) only access existing elements; they don't insert new ones. Therefore, they can safely return references without violating std::unique_ptr's ownership rules.
Now, go ahead and grab that reference without worrying about copying your precious std::unique_ptr!
Here's a complete example:
cpp
#include <QHash>
#include <memory>
#include <iostream>
class MyClass {
public:
MyClass(int x) : x_(x) { std::cout << "MyClass(" << x_ << ")\n"; }
~MyClass() { std::cout << "~MyClass(" << x_ << ")\n"; }
int value() const { return x_; }
private:
int x_;
};
int main() {
QHash<int, std::unique_ptr<MyClass>> hash;
hash[1] = std::make_unique<MyClass>(10);
hash[2] = std::make_unique<MyClass>(20);
// Using value()
std::unique_ptr<MyClass>& ref1 = hash.value(1);
std::cout << "Value at key 1: " << ref1->value() << "\n";
// Using find()
auto it = hash.find(2);
if (it != hash.end()) {
std::unique_ptr<MyClass>& ref2 = *it;
std::cout << "Value at key 2: " << ref2->value() << "\n";
}
return 0; // MyClass instances are properly destroyed here
}
Happy coding with Qt and C++17!
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
You're close, but indeed, that one-liner is not entirely safe.
Here's why:
hash.constFind(id) returns a QHash::const_iterator.
If id is not found in the hash, constFind() returns hash.constEnd(), which is a special "past-the-end" iterator value.
Calling value() on hash.constEnd() is undefined behavior (UB). It's like dereferencing a null or invalid pointer.
So, your proposed line:
cpp
return hash.constFind(id).value().get(); // NOT SAFE
will likely crash or produce garbage if id is not in the hash, because you're blindly calling value() without checking the iterator's validity.
The idiomatic way:
To safely return the raw pointer (or nullptr if not found), you must check the iterator against constEnd()before accessing the value. Here's the fixed, two-step version:
cpp
auto it = hash.constFind(id);
return (it != hash.constEnd()) ? it->get() : nullptr;
Let's break it down:
auto it = hash.constFind(id); searches for id and stores the iterator in it.
it != hash.constEnd() checks if the iterator is valid (i.e., id was found).
If true (id found): it->get() returns the raw pointer managed by the std::unique_ptr ( equivalent to (*it).get() ). The -> operator dereferences the iterator to access the std::unique_ptr, and get() extracts the raw pointer.
If false (id not found): the expression evaluates to nullptr.
This pattern is concise, readable, and safe.
Why it->get() instead of it.value().get()?
Both work, but it->get() is slightly more efficient and modern-C++-idiomatic:
it.value() returns a copy of the std::unique_ptr (not a reference, surprisingly!). Then, get() is called on that temporary copy. The copy is immediately discarded.
it->get() (or (*it).get()) directly accesses the stored std::unique_ptr via the iterator, avoiding the unnecessary copy.
Wrap it in a function (optional but nice)
If this pattern is used frequently, consider a tiny helper function: