Implicit Shared Class vs std::unique/shared pointer
-
Hey,
I try to get my head around Implicit shared classes (QSharedDataPointer) and there pro and cons.
Implicit shared classes are widly used in Qt (f.e. QString) and i know that they are a "copy on access" pattern.
Since C++ 11, there are many new options and i have some decision problems which technique i should use f.e. a shared pointer or a unique pointer instead of implicit sharing.Can anybody tell me the best practice/scenarios when i should use implict share over unique/shared pointer?
Thanks in advance
Tonka -
The purpose of each of these types is quite different.
unique_ptr is meant as a light replacement for the new/delete blocks with shady ownership. Qt has a QScopedPointer that works similarly but was invented before unique_ptr and move semantics were introduced in c++11. As it's name suggests you should use them for objects that have a specific and unique lifetime specification. The pointer is the managing object and is the only one that can delete the data it points to. All other accesses to that data should be via raw or weak pointers.
shared_ptr has a Qt counterpart in QSharedPointer. It is a heavier, thread safe, reference counted object that shares ownership of some data. This should be used when you have data shared between objects of different lifetimes, and the data should live as long as the last one of these objects.
QSharedDataPointer has no counterpart in the standard. shared_ptr can be used to implement it but it has extra functionality - the detach it can perform on write. This should obviously be used for implicit sharing like scenarios.
As to when to use implicit sharing at all? That's not something that can be answered easily. Definitely don't use it for small data types like ints or small structs. The cost of overhead will shadow any benefits. A good candidates are data types with large, dynamically allocated resources, for which a copy is expensive.
One of the cons of implicit sharing is that it's hard to keep track of when the detach happens, as it's intentionally made so that it is done invisibly to the user. If you need that level of resource control implicitly shared class is not a good idea, as you want to be clear in the interface about when an expensive copy occurs.