How to deep copy QMap and other Qt containers
Asked Answered
F

1

9

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.

Flitter answered 28/5, 2013 at 19:45 Comment(9)
The above code works fine for me - why do you think it won't?Transude
@Transude I have run it through GDB and seen that both maps contain "value2"Flitter
Yes, I misread the code at first, this snippet should work fine. Deleting my answer.Stour
Once again, not for me - and I'm also using Qt 4.8 (4.8.4 x64 Linux to be precise). Can you post the full code you are using to test this? QMap is implicitly shared, but as soon as you modify it, the COW mechanism will kick in and a deep copy will occur (disregarding QString's implicit sharing of course).Transude
Works fine also with Qt 5.1 in Linux.Brotherly
@Transude Yes I can post the full code. I'll need to sanitize a couple of things and then I'll post. ThanksFlitter
How about adding Q_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
@Roku I added the Q_ASSERT you suggested and sure enough it is failing. Now the quest moves on it that direction. I'll update the question when I'm finished for future travelers.Flitter
@Transude I found the issue and it was not with Qt. Nevertheless I think the question (revised to remove non-applicable code) may be helpful to others in the future. Do you want to post an answer based on your comment? If so, I'll accept it. Thanks for your help.Flitter
A
20

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();
Aceae answered 2/7, 2014 at 11:55 Comment(3)
Awesome. This is the answerFlitter
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.