Generally speaking, what is the correct way to deep copy Qt containers? I'm not worried about deep copying the containers recursively, although addressing such would be helpful.
How to deep copy QMap and other Qt containers
Despite what everyone will tell you - that you don't deep copy Qt containers - there are situations in which you simply need to perform an actual deep copy instead of just a shallow one. To do that, use detach()
:
container1 = container2;
container1.detach();
Awesome. This is the answer –
Flitter
Can you give an example of when you would need to do this? The moment you modify
container1
it would perform a deep copy, if you don't modify it - why would you want to copy it!? –
Transude @Transude Just yesterday I needed to do exactly that. I have two threads, one receives data over a channel (similar to socket), process the data and stores it in a couple of containers. The other thread renders the data by periodically checking for new data. If there are new data, it locks a mutex and copies data from some of the containers - this is where I need to deep-copy. If I didn't perform deep copy, locking would be done for each of the containers seperately when the data processing thread modifies them, which would degrade performance. –
Aceae
© 2022 - 2024 — McMap. All rights reserved.
QMap
is implicitly shared, but as soon as you modify it, the COW mechanism will kick in and a deep copy will occur (disregardingQString
's implicit sharing of course). – TransudeQ_ASSERT(_savedMap[modelToSave] != _modifiedMap[modelToSave]);
between first and second line (not counting comment lines). Just to check that you are really making some changes to the map. – Brotherly