i have the following problem, i am using
Q_DECLARE_METATYPE( std::shared_ptr<int> );
qRegisterMetaType< std::shared_ptr<int> >();
QMetaType::registerComparators< std::shared_ptr<int> >();
to use std::shared_ptr<int>
with e.g. QListModel.
I need a behavior where
QVariant::fromValue( std::shared_ptr<int>( new int(5) ) ) == QVariant::fromValue( std::shared_ptr<int>( new int(5) ) )
is true. My code above return false here since std::shared_ptr<int>::operator== ()
compares the raw pointers. is it possible to register comparators other than the standard operators in QMetaType::registerComparators
?
By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).
When we create an object with new operator in shared_ptr there will be two dynamic memory allocations that happen, one for object from the new and the second is the manager object created by the shared_ptr constructor. Since memory allocations are slow, creating shared_ptr is slow when compared to raw pointer.
All the instances point to the same object, and share access to one "control block" that increments and decrements the reference count whenever a new shared_ptr is added, goes out of scope, or is reset. When the reference count reaches zero, the control block deletes the memory resource and itself.
The ownership of an object can only be shared with another shared_ptr by copy constructing or copy assigning its value to another shared_ptr .
You could try using registerConverter()
to allow implicit conversion of the shared_ptr<int>
to a regular int, and compare them that way. Obviously then you would not do registerComparator()
. An alternative would be to wrap shared_ptr<int>
in your own class and implement comparison the way you want.
Or check out Q_DECLARE_SMART_POINTER_METATYPE
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With