Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QVariant with std::shared_ptr

Tags:

c++

qt

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?

like image 294
choosyg Avatar asked Mar 05 '14 14:03

choosyg


People also ask

What happens when you move shared_ptr?

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).

Is shared_ptr slow?

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.

What happens when shared_ptr goes out of scope?

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.

Is shared_ptr copyable?

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 .


1 Answers

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.

like image 196
John Zwinck Avatar answered Oct 31 '22 03:10

John Zwinck