In C++17 Qt5.15 snippet, I have a QHash of <int, std::unique_ptr>, I can access the values with constFind but the build errors with error C2280: 'std::unique_ptr<MyClass,std::default_delete>::unique_ptr(const std::unique_ptr<MyClass,std::default_delete> &)': attempting to reference a deleted function
I don't want to use shared_ptr just because the QHash is stubborn like this, what would you suggest?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The problem is that QHash::constFind() (and other Qt container methods) return a copy of the value associated with the key. Since your value type is std::unique_ptr<MyClass>, the compiler tries to generate a copy constructor for it, which is deleted by the C++ Standard Library because unique_ptr is, well, unique!
You can't copy a unique_ptr, only move it. Hence the error C2280.
Now, let's explore the solutions that don't involve switching to shared_ptr (a perfectly valid choice, btw, but I understand your reluctance).
1. Use QHash::value() with a const reference
Instead of constFind(), use QHash::value() like this:
cpp
auto& myValue = myHash.value(myKey);
Here, value() returns a const reference to the unique_ptr (not a copy!). The auto& deduces the type to const std::unique_ptr<MyClass>&, which is fine.
2. Use iterators (the Qt way)
Get an iterator to the element using QHash::find() (not constFind()):
cpp
auto it = myHash.find(myKey);
if (it != myHash.end()) {
const std::unique_ptr<MyClass>& myValue = it.value(); // or simply: auto& myValue = *it;
// use myValue
}
The iterator it points to a QHash::const_iterator which holds a reference to the unique_ptr (accessible via it.value() or simply dereferencing *it).
3. Use std::unordered_map instead of QHash
If you're comfortable with the Standard Library containers, switch to std::unordered_map<int, std::unique_ptr<MyClass>>. Its find() method returns an iterator, just like Qt's, and you can use it similarly:
cpp
auto it = myMap.find(myKey);
if (it != myMap.end()) {
const std::unique_ptr<MyClass>& myValue = it->second;
// use myValue
}
4. (ugly) Cast away const-ness (Don't do this at home!)
I strongly advise against this, but for completeness: You can use const_cast to cast the copied unique_ptr to a non-const reference, allowing you to move from it (not copy!). This is undefined behavior if the original unique_ptr is actually const, so don't say I didn't warn you...
cpp
auto found = myHash.constFind(myKey);
if (found != myHash.cend()) {
std::unique_ptr<MyClass> myValue = std::move(const_cast<std::unique_ptr<MyClass>&>(*found));
// myValue now holds the pointer (original hash entry is reset to nullptr)
}
Don't use this last option. It's a hack that will make your code harder to understand and maintain.
Stick with options 1 or 2. They're clean, idiomatic, and efficient.
well, the issue doesn't arise when rerturning the value (which is a reference) but here:
code
template <typename ...Args>
iterator emplace(Key &&key, Args &&... args)
{
if (isDetached()) {
if (d->shouldGrow()) // Construct the value now so that no dangling references are used
return emplace_helper(std::move(key), T(std::forward<Args>(args)...));
return emplace_helper(std::move(key), std::forward<Args>(args)...);
}
// else: we must detach
const auto copy = *this; // keep 'args' alive across the detach/growth
detach();
return emplace_helper(std::move(key), std::forward<Args>(args)...);
}
Assistant
The real culprit!
You're absolutely right; the issue doesn't lie in returning a reference, but rather in this QHash::emplace() implementation, specifically in this line:
The compiler attempts to copy-initialize this temporary unique_ptr from the forwarded args.... Since args... contains (at least) one std::unique_ptr<MyClass> (from std::make_unique<MyClass>() or similar), the compiler tries to copy that unique_ptr, which, as we know, is not allowed (the copy constructor is deleted).
The std::forward<Args>(args)... is a parameter pack expansion, which, in this case, tries to invoke the unique_ptr constructor like this:
cpp
std::unique_ptr<MyClass>(/* forwarded args */)
When Args contains a std::unique_ptr<MyClass>, this becomes:
cpp
std::unique_ptr<MyClass>(std::unique_ptr<MyClass>&&) // (1)
// or
std::unique_ptr<MyClass>(const std::unique_ptr<MyClass>&) // (2)
(1) is the move constructor, which is fine.
(2) is the copy constructor, which is deleted and causes the error C2280.
The Qt developers assumed that the value type T can be copy-initialized from the forwarded arguments, which is not true for std::unique_ptr.
Those methods take a T (i.e., std::unique_ptr<MyClass>) directly as an argument, like this:
cpp
iterator insert(const Key &key, T &&value) // or operator[]=(T &&value)
Here, the caller must provide a std::unique_ptr<MyClass> rvalue (e.g., std::make_unique<MyClass>()), which is moved into the hash. No temporary T object is created by the hash itself, avoiding the copy-init issue.
Workaround (hack): Specialize QHash for std::unique_ptr
You can partially specializeQHash for std::unique_ptr to bypass this issue. This is a Qt-specific hack and not recommended for general use, but it solves your problem:
Add this code before including any Qt headers. This specialization tells QHash to use construct() instead of the default T(std::forward<Args>(args)...) when emplacing a std::unique_ptr.
With this specialization, emplace() will work like this:
cpp
myHash.emplace(42, new MyClass()); // or MyClass(args...)
Not ideal, as it requires new, but it avoids the copy-init issue.
Alternative: Patch Qt (if you can)
If you're building Qt from sources or using a custom Qt fork, you can patchqhash.h to handle move-only types like std::unique_ptr. Update the emplace_helper() call to:
By removing the T(...) wrapper, you ensure that the forwarded arguments are directly moved into the QHash node, avoiding the copy-init problem.
Long-term solution: Qt6
In Qt6, the container implementations have been overhauled to support move-only types properly. If feasible, consider migrating to Qt6, where this issue should be resolved.
I hope this detailed explanation helps you understand the root cause. Choose the workaround that best fits your project's constraints. Happy coding!