qsharedpointer example. If somehow the object/container survives so does the smart pointer and the allocated memory. qsharedpointer example

 
 If somehow the object/container survives so does the smart pointer and the allocated memoryqsharedpointer example  The latter is almost a drop-in replacement for the former, except that you can’t pass a QSharedPointer to QObject::connect

In my project I create QObject instances and give them a parent-child relationship. In this example, the source object is a simple binary switch that toggles its state based on a timer. In all other cases an invalid. Guarded pointers are useful whenever you need to store a pointer. It is a bug if you put just a pointer to your item to QChache and at the same time such pointer is managed by QSharedPointer. QSharedPointer<MyClass> mc (new MyClass ()); mc->testSharedThis (); QScopedPointer's second template parameter can be used for custom cleanup handlers. The example will output 1, 2, 3 in that order. 1. You can rate examples to help us improve the quality of examples. In this video series we will cover Qt 6. QSharedPointer:: QSharedPointer (const QWeakPointer < T > &other) Creates a QSharedPointer by promoting the weak reference other to strong reference and sharing. That said, your stack trace is really strange:. See QWeakPointer::toStrongRef() for an example. The d pointer points to an object of this type. example, this allows calling QObject::deleteLater() on a given object. In your example "going out of scope" is happening when closing brace of main () function is encountered. 6. You can rate examples to help us improve the quality of examples. That said, your stack trace is really strange:. Frequently Used Methods. I see that QSharedPointer keeps my data valid if the acquisition threads stop during data is processing. Copy assigns from other and returns a reference to this object. A minimal example: Q_DECLARE_METATYPE(QSharedPointer<const QObject>);One example may be the case where you store lots of pointers to objects in a container class. Add a comment. It behaves exactly like a normal pointer for normal purposes, including respect for constness. One of the important member functions of QSharedPointer is isNull(), which returns true if the pointer is null, and false otherwise. Also, this Q_DECLARE_METATYPE(SharedTestClass) shouldn't be needed. Define the EmployeeData class derived from. Also, this Q_DECLARE_METATYPE(SharedTestClass) shouldn't be needed. The QSharedPointer class holds a strong reference to a shared pointer More. But, it all depends on your use case. QSharedPointer:: objectCast() works reliably across DLL boundaries, but QSharedPointer:: dynamicCast() and std::dynamic_pointer_cast() don’t. Looking for examples of natural languages with affricates but no corresponding fricatives/plosivesMember Function Documentation QSharedPointer < T > QEnableSharedFromThis:: sharedFromThis (). // Create pointer in constructor. The QSharedPointer is an automatic, shared pointer in C++. QSharedPointer<A> pA1 (new A, & A ::f); To copy to clipboard, switch view to plain text mode. First of all, could anyone please give me an example where you would ACTUALLY use shared pointers. On programm exit i have 2 destructor calls for GeTokenItem and one more that invokes acces violation. 9. This function was introduced in Qt 5. One problem i have ran into is using signals and slots with the objects that are shared-pointed-to. Actually, it does so in examples setting custom deleter to Object::deleteLater . _pointer = QSharedPointer<APIRequest> (this);For example: @ QSharedPointer<QToolButton>(new QToolButton);@ I have been trying to make this work properly within a psuedo widget factory i have made( as the application has thousands of widgets) and I want to make sure that the memory is de-allocated properly. 5. See also QSharedPointer and QScopedPointer. If a ptr2's template parameter is different from a ptr1's, 1008. h","path":"src/corelib/tools/qalgorithms. Not sure I got you there. But indeed Qt is leaking the functor object. It. If you refactor your code so that all new operator are in lines like these, all your problems will be solved. When an object gets deleted, either by delete childObject; or delete parentObject;, I would like the QSharedPointer instances to return true when calling isNull(). one pointer (for example, QSharedPointer). QSharedPointer is a smart. Both examples will crash when the first destructor is called. Yes. The Qt docs say that Q_DECLARE_METATYPE is necessary in case one has a connect being a queued connection. QSharedPointer는 C++의 자동 공유 포인터입니다. Before I use QSharedPointer, I am used to use forward declaration to declare my class instead of include its . The memory corruption can happen if Team object is destroyed before reading its pointer from QMap. the above one did not compile with msvc17 and with my arm toolchain. However, if you really need to differentiate between. The example is not complete. That's what's meant with "object is null" isNull() and operator!() are equivalent, you can use either one. See also QSharedPointer and QPointer. Aug 27, 2015 at 15:02. 4. Any pointer class which takes responsibility for the lifetime of the object it points to is considered a smart pointer. Detailed Description. The exception is pointers derived from QObject: in that. referencing it. 212: 213: This class is never instantiated directly: the constructors and: 214In the example above, the template specialization for the clone() function calls the EmployeeData::clone() virtual function. data (); } When you delete the pointed-to object, data () will be null. QSharedPointer:: objectCast() works reliably across DLL boundaries, but QSharedPointer:: dynamicCast() and std::dynamic_pointer_cast() don’t. [quote author="situ117" date="1304279927"] I was reading about QSharedPointer in Qt. The first MyClass object pointer 0x13defe0 is assigned to the QPointer instance, the second one (0x110f780) to QSharedPointer instance. [/quote] There are not so much Qt examples and demos with QSharedPointer because of the general con. [/quote] That is a good example to be careful with smart pointers. 1 Answer. referencing it. It uses reference counting to track the number of objects sharing the pointer, and. C++ (Cpp) QSharedPointer::at - 10 examples found. So the point is: don't use QSharedPointer just because it's smart. QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it. You can rate examples to help us improve the quality of examples. List of all members, including inherited members; Public FunctionsA "null" QSharedPointer wraps a T* t where t equals 0/NULL/nullptr. Smart pointers facilitate the dynamic memory operations. If this (that is, the subclass instance invoking this method) is being managed by a QSharedPointer, returns a shared pointer instance pointing to this; otherwise returns a QSharedPointer holding a null pointer. 8. If on the other hand %h is available, the minutes will wrap around to zero after 59 and the time will carry to the hour. QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and. QScopedPointer intentionally has no copy constructor or assignment operator, such that ownership and. . reset (rawFoo); But as mentioned in the beginning, these are not equal. Smart pointers facilitate the dynamic memory operations. The shared pointer will automatically destroy its contents only when there are no shared pointers referencing the object originally created for the shared pointer. You can't assign two pointers to each other, but you can explicitly transfer the ownership of. The latter is almost a drop-in replacement for the former, except that you can’t pass a QSharedPointer to QObject::connect. A more complex program sending QSharePointer objects using slots has a similar situation with GDB, that can be reproduced with the previous example. You can rate examples to help us improve the quality of. So, at least, QList and QVector can be filled with it (I am not trying to find high-speed approach). Usually one puts this (note that the typedefed name is used as string argument): qRegisterMetaType< QSharedPointer<TestClass> > ( "SharedTestClass" );My intention was, since I had to store the actual data in another QSharedPointer, to make a connect on that shared pointer that tells the other widget. You shouldn't do that even from C++. The QSharedPointer is an automatic, shared pointer in C++. Smart pointers on the other hand, is more a category than a specific type, including shared pointers, auto. The Qt documentation suggests that using the QSharedDataPointer with a visible implementation of its inferior is not typical. The temporary instance of the shared pointer allocated on the heap in answer1 will be deallocated by its shared pointer. QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it. There are not so much Qt examples and demos with QSharedPointer because of the general concept for memory management in Qt using parent–child hierarchy of QObject. {"payload":{"allShortcutsEnabled":false,"fileTree":{"src/corelib/tools":{"items":[{"name":"qalgorithms. C++ (Cpp) QSharedPointer::GetSubscriptionTypeStr - 2 examples found. I have QList<QSharedPointer<MyClass>>. It behaves exactly like a normal pointer for normal purposes, including respect for constness. If you want a container class that provides a fast prepend() function, use QList or QLinkedList instead. Examples at hotexamples. A class derived from EmployeeData could override that function and return the proper polymorphic type. As is stated in Qt documentation the == operator of QSharedPointer returns true if the values of the two managed raw pointers have the same value. The exception is pointers derived from QObject: in that. Simple CBOR stream decoder, operating on either a QByteArray or QIODevice. All of QList's functionality also applies to QQueue. If you have 2 separate threads that are doing. 0. See QWeakPointer::toStrongRef() for an example. Example. This blog post is the first in a series that will cover using OpenGL with Qt. These are the top rated real world C++ (Cpp) examples of QSharedPointer::UpdateViewSection extracted from open source projects. This function was introduced in Qt 4. That said, yo. – Igor Tandetnik. If somehow the object/container survives so does the smart pointer and the allocated memory. And how would you pass a shared pointer to another function or create an object with a shared pointer. Since the replicas have the same properties, signals, and slots as were. It has all the features you may want in a modern pointer class: it is polymorphic, it supports static, const, and dynamic casts, it implements atomic reference-counting and thread-safe semantics, it supports. 4. Here is my class function: template<class T> QSharedPointer<T> getObjectWithId ( int id ) { QSharedPointer<SqlObject> obj = getObjectWithId ( T::staticMetaObject. h","contentType":"file. To complicate it even more, all debugging traces were leading to. There are several ways to avoid the problem in this particular example I can think of: change Test destructor to expect null m, write template template<typename T> inline T no_move (T&& tmp) {return tmp;}, explicitly create temporary Test object in assign, add getter for m and call it to force copying m (advised by Jarod42 ); MS Visual Studio. Qt 6 youtube videos by Bry. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely. To have that guarantee, use toStrongRef(), which returns a QSharedPointer object. This QCPAxisTicker subclass generates ticks with a fixed tick step set with setTickStep. The contents of the object pointed to by the pointer should not considered shared, however: there is. ) method. You can rate examples to help us improve the quality of. It behaves exactly like a normal pointer for normal purposes, including respect for constness. behaves exactly like a normal pointer for normal purposes, including respect for constness. The title can be styled using the. For QSharedPointer . The others are more specialized. It is also possible to allow integer multiples and integer powers of the specified tick step with setScaleStrategy. 4, but was reborn in 4. 2 Answers Sorted by: 4 You can create a custom connect function: template<class T> bool my_connect (const QSharedPointer<T> &sender, const char. I worked around this by extracting a raw pointer from the QSharedPointer: The template parameter is the type T of the class which QSharedPointer tracks. QSharedPointer has no knowledge about that incident and will not set the pointer to 0 automatically. The ticker of an axis can be set via QCPAxis::setTicker. But, it all depends on your use case. QExplicitlySharedDataPointer, QScopedPointer, and QSharedPointer. For example, one can have a list of QStrings QList<QSharedPointer<QString> > queue. Before drawing you would create a local QSharedPointer<MyClass> in the drawing function and check if it is valid. Note that if you intend to use the type in queued signal and slot connections or in QObject's property system, you. It behaves exactly like a normal pointer for normal purposes, including respect for constness. It behaves exactly like a normal pointer for normal purposes, including respect for constness. C++ (Cpp) QSharedPointer::isNull - 30 examples found. If the current QSharedPointer is not a nullptr, then the internal reference count is decremented. exec () (which represents the main event loop of Qt App) has already. removeAll(dataPoint01); }. Examples of such functions include std::static_pointer_cast, custom comparators, or predicates. Re: Custom Deleter for QSharedPointer. QSharedDataPointer has a very specific use-case, which is where you want to share data between instances, with copy-on-write behaviour - that is, as soon as one instance, tries to modify it, it detaches and it now has it's own separate copy. MyObject * obj = sharedPointerToObject. That said, your stack trace is really strange:. So it this allows multiple pointers to point to the same class instance. className(), id ); return qSharedPointerCast<T> (. Example: QPointer < QLabel > label = new QLabel ; label - > setText( "&Status:" );. I would still recommend you to use 2/3, as. A shared pointer is null by default, or when set to 0/nullptr explicitly:C++ (Cpp) QSharedPointer::node - 2 examples found. There are not so much Qt examples and demos with QSharedPointer because of the general concept for memory management in Qt using parent–child hierarchy of QObject. QTest. QSharedPointer:: QSharedPointer (const QWeakPointer < T > &other) Creates a QSharedPointer by promoting the weak reference other to strong reference and sharing its pointer. But you might miss the more convenient BlockingQueue in Java/Python. > You can for example return the result of qHash(sharedPointer. : QFrame: Supports the box model. append(QSharedPointer<MyObject>(new MyObject("second", 2))); Share. One example may be the case where you store lots of pointers to objects in a container class. It behaves exactly like a normal pointer for normal purposes, including respect for constness. For instance, the method index returns a QModelIndex that takes a void pointer in the constructor, pointing to one of those. out of scope, provided no other QSharedPointer objects are. This example creates a QSharedPointer object that references an int value. Someone has to manage the memory. I like passing data between threads using QSharedDataPointer or QSharedPointer. : new MyGizmo. Member Type Documentation typedef QSharedDataPointer:: Type. maturity); by now, standard-library shared pointers are by far the. There are not so much Qt examples and demos with QSharedPointer because of the general concept for memory management in Qt using parent–child hierarchy of QObject. QtTest. Detailed Description. Previously i had done this: Qt Code: Switch view. Just a small addition. This is the complete list of members for QSharedPointer, including inherited members. Depending on your use case that might be a better. /blocking_queue. QSharedPointer is an EXTERNAL to the class and implements a reference counting pointer to a single instance of a class. QSharedPointer. A QSharedPointer object can be created from a. qt. For example, canConvert(QMetaType::fromType<int>()) would return true when called on a variant containing a string because, in principle, QVariant is able to convert strings of numbers to integers. Maybe you want to collect for example "time:", "accuracy:" or "position:" samples for your particular use case. It's a start. The procedure is: Define the class Employee to have a single data member of type QSharedDataPointer<EmployeeData>. . The QSharedPointer is an automatic, shared pointer in C++. You can inherit this class when you need to create a QSharedPointer from any instance of a class; for instance, from within the object itself. The following examples can all be compiled and run independently. When the code block containing ptr2 ends, its reference. e. I was reading about QSharedPointer in Qt. These are the top rated real world C++ (Cpp) examples of QSharedPointer::node extracted from open source projects. Also, this Q_DECLARE_METATYPE(SharedTestClass) shouldn't be needed. For example, one can have a list of QStrings QList<QSharedPointer<QString> > queue. Note that QWeakPointers created this way on arbitrary QObjects usually cannot be promoted to QSharedPointer. 1 Reply Last reply . qRegisterMetaType< QSharedPointer<TestClass> >("SharedTestClass"); in main() not as a global variable. 12. It is similar to std::shared_ptr in C++. I use C++17, GCC 7. 04 OS. e. Combining this with QSharedPointer for example might result in multiple object free or access after free kind of problems. C++ (Cpp) QSharedPointer::GetP2 - 2 examples found. QSharedPointer will attempt to perform an automatic t static_cast. Qt Code: Switch view. It stores its items in adjacent memory locations and provides fast index-based access. A little example would be. Does my QSharedPointer is always valid ? What append if during processing (MainWindow), the usb_read() occurs and the memcpy write on my image. To avoid passing raw pointers around I have changed all occurrences of DataProvider * to QSharedPointer<DataProvider>. It behaves exactly like a normal pointer for normal purposes, including respect for constness. For example, consider a segment which directly goes from region 4 to 2 but originally is far out to the top left such that it doesn't cross region 5. A smart pointer is an abstract data type that has all features of a standard pointer and additionally provides automatic garbage collection. ©2023 The Qt Company Ltd. 04 and in my application I need to use QSharedPointer together with the appropriate dynamic_cast (object_cast) conversions at runtime. class QSharedPointer< T > The QSharedPointer class stores a pointer to a potentially shared object. But just added a basic example from the docs to make things clear. QSharedPointer<QMap<int, bool>> mpsptr = QSharedPointer<QMap<int, bool>>::create (QMap<int, bool> { {1, false}}); Ok, I found an answer that works for me. So QSharedPointer was shelved for 4. See the typdefs Promise::Ptr, Deferred::Ptr etc. The one I used in my own answer does. out of scope, provided no other QSharedPointer objects are. 1 Answer. 1 Reply Last reply . This function was introduced in Qt 6. Previously i had done this: Code: MyObject * object; // Subclass of QObject. The point is that the internal connection list is simply marked as dirty, and not cleared until either the sender is deleted or a new signal is connected (see the usages of cleanConnectionLists). Qt로 프로그래밍할 때 메모리 관리 문제 (메모리 관리 불량으로 인한 메모리 누수 및 버그. 04: class QSharedPointer<VideoItemPrivate> has no member named ‘get’ Hello everyone, I'm trying to install gst-plugins-good 1. But everytime i try to implement this i recieve a seg fault. For the sake of the example: Don't return a pointer to QList<>, return the QList<> itself. LMNode::setParent(const QSharedPointer<LMNode>& parent) { this->parent = parent; } const QSharedPointer<LMNode>& LMNode::getParent() { return this->parent; } Sure, in the second version i avoid the increment of the reference counter and the changing of the QSharedPointer object. A class derived from EmployeeData could override that function and return the proper polymorphic type. QVector<T> used to be a different class in Qt 5, but is now a simple alias to QList. #include <QSharedPointer> Note: All functions in this class are reentrant. or if you already have a reference to a pointer, then use the reset () method as follows: Qsharedfoo. For some reason, there are very few examples out there on how to use QSharedPointer, so i find myself posting here. Your solution is simple. C++ (Cpp) QSharedPointer::GetCenter - 3 examples found. get ()); Have a look at the documentation of std::make_shared (for example here ). no known conversion for argument 1 from 'const RecordPtr {aka const QSharedPointer<MyApp::Record>}' to 'const QObject*' you are trying to pass an object of type RecordPtr to a method expecting "const QObject*". Qt Blocking Queue. wysota. A base class that allows obtaining a QSharedPointer for an object already managed by a shared pointer. If the reference count is zero then the object it is pointing to will be destroyed. This function was introduced in Qt 4. The base class tick generator used by QCPAxis to create tick positions and tick labels. MyClass * myIns = new MyClass (); QSharedPointer<MyClass> asp ( myIns); QVariant aVariant = QVariant::fromValue( asp); To copy to clipboard, switch view to plain text mode. The QSharedPointer is an automatic, shared pointer in C++. QSharedPointer will attempt to perform an automatic t static_cast. It behaves exactly like a normal pointer for normal purposes, including respect for constness. the above one did not compile with msvc17 and with my arm toolchain. In the example above, the template specialization for the clone() function calls the EmployeeData::clone() virtual function. These conversions are called in a shared object which is properly loaded at runtime. QSharedPointer/QPointer: use SerializerBase::registerPointerConverters<T>()QSharedPointer documentation does not have any warning about pointing to QObject-derived classes. I guess, it can conflict with Qt's parent/child mechanism. qRegisterMetaType< QSharedPointer<TestClass> >("SharedTestClass"); in main() not as a global variable. You can rate examples to help us improve the quality of examples. when I will print the debug message second time it shows the segmentation fault and application crashes. As reference the example tested on cross environment using GDB:I'm trying to use QSharedPointer to define an object that will be created in a thread that will emit a signal to another thread. h" typedef BlockingQueue<QByteArray> MessageQueue; class. centralwidget = std::make_shared<QWidget> (MainWindow); verticalLayout = std::make_shared<QVBoxLayout> (centralwidget. Test this small example: @ #include <QSharedPointer> class CTest {int INum; public: CTest(): INum ( 0 ) {} int. staticCast<Switch> (); Both versions are basically equivalent to doing static_cast on raw pointers. QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it. data(); delete obj; To copy to clipboard, switch view to plain text mode. As long as the shared pointer is in static mutexes map, it will never be deallocated, and the lifetime of mutexes is the lifetime of the program. Of course this can be extended with more tags such as "sample:" if you want to collect many different sets of data at once. qRegisterMetaType is required for the queued connection. QWeakPointer objects can only be created by assignment from a QSharedPointer. qRegisterMetaType< QSharedPointer<TestClass> >("SharedTestClass"); in main() not as a global variable. This is a working example showing it calls. A class derived from EmployeeData could override that function and return the proper polymorphic type. > Regards, > > Alex > > > Rudenko Eugene a écrit : >> Hello. // Create a fresh shared pointer in the scope QSharedPointer<uint8_t> image(new uint8_t[IMG_SIZE]); // the ring buffer can possibly be rewritten on the next usb_read() (if bufferlength = 1) so I copy. When removeData() returns, any further attempts to reference the sender is undefined behavior. The QSharedPointer is an automatic, shared pointer in C++. The same is for tokencount == 1. The example above tests that mkdir() outputs the right warning when invoked with an invalid file name. Improve this answer. id), name(other. bool operator== ( const QSharedPointer & ptr1, const QSharedPointer & ptr2 ) Returns true if the pointer referenced by ptr1 is the same pointer as that referenced by ptr2. For some reason, there are very few examples out there on how to use QSharedPointer, so i find myself posting here. That means they should have a default constructor, a copy constructor, and an assignment operator. As reference the example tested on cross environment using GDB:I was reading about QSharedPointer in Qt. You can rate examples to help us improve the quality of examples. You can however easily fix that by creating a new shared pointer instance for each sample and pass that one to the other thread in the signal. In many cases, that UB may be innocuous, but it is UB regardless. AnotherObject * something; The c++ (cpp) qsharedpointer example is extracted from the most popular open source projects, you can refer to the following example for usage. 4. 1. docx from EEET 1026 at University of South Australia. Usually one puts this (note that the typedefed name is used as string argument): qRegisterMetaType< QSharedPointer >("SharedTestClass"); in main() not as a global variable. The QWeakPointer is QSharedPointer 's cousin. QSharedPointer: pointer 0x2384d70 already has reference counting Which at the very least gives us a basic idea that there is something wrong, and it involves a QSharedPointer. The examples on Wikipedia makes no sense to me. For. h: > > // ### Qt6: Using a private here has high impact on runtime > // on users such as QFileInfo. The QWeakPointer is an automatic weak reference to a pointer in C++. 209: The pointer to the object is kept here because it needs to match the actual: 210: deleter function's parameters, regardless of what template argument the: 211: last QSharedPointer instance had. Modifying the data in the container will then affect all curves that share the container. These are the top rated real world C++ (Cpp) examples of QSharedPointer::GetSubscriptionTypeStr extracted from open source projects. C++ (Cpp) QSharedPointer::direction - 6 examples found. [quote author="situ117" date="1304279927"] I was reading about QSharedPointer in Qt. The QWeakPointer is an automatic weak reference to a pointer in C++. Qt 6 youtube videos by Bry. Qt also provides QSharedPointer, an implementation of a reference-counted shared pointer object, which can be used to maintain a collection of references to an individual pointer. The QPointer class is a template class that provides guarded pointers to QObject. 1. It behaves exactly like a normal pointer for normal purposes, including respect for constness. [noexcept] const T *QSharedDataPointer:: constData const. . The source can be found in the examples directory: examples/tutorials/threads/ Example 1: Using the Thread Pool. It adds only one member to its parent, which is of type T (the actual type, not a pointer to it). Qt Base (Core, Gui, Widgets, Network,. QSharedPointer is a smart pointer class in Qt that provides shared ownership of objects. Example usage - #include <QSharedData> #include <QString> class EmployeeData : public QSharedData { public: EmployeeData() : id(-1) { }. Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions and tick labels for the current axis range. The QSharedPointer is an automatic, shared pointer in C++. QWeakPointer objects can only be created by assignment from a QSharedPointer. Sabat 10 Jan 2020, 10:52. If it represents a type, it returns QMetaType::Int. Expert Help. If you type is base on QObject, you have to take care to avoid double free if they have a parent. ) summary refs log tree commit diff statsQMetaType::construct (), QMetaType::sizeOf (), and QMetaType::alignOf. These are the top rated real world C++ (Cpp) examples of QSharedPointer::isSelected extracted from open source projects. See QWeakPointer::toStrongRef() for an example. Otherwise, the object deletes itself after emitting the signal. A public static factory method returning in this case QSharedPointer; A private deleter class that is a friend of class A; Here is an example using boost::shared_ptr (I do not have a QT installation right now, but you should be able to just replace all instances of boost::shared_ptr with QSharedPointer)It is somehow reasonable to use QSharedPointer here. But I've not seen it much in use in source code of Examples and Demos. Immediately after construction both pointers go out of scope. The QSharedPointer is an automatic, shared pointer in C++. If a ptr2's. That said, your stack trace is really strange:. All these news and deletes bothered me when I started in Qt, and I tried to stick to how I did it in gtkmm before. QSharedPointer dynamicCast and objectCast fail on ubuntu. @Yakk: Thanks for that, I've updated my answer to reflect your point. Use qSharedPointerCast (): QSharedPointer <Switch> mySwitchTest= qSharedPointerCast<Switch> (myState); Or call staticCast () on the smart pointer: QSharedPointer <Switch> mySwitchTest= myState. The QSharedPointer is an automatic, shared pointer in C++. 209: The pointer to the object is kept here because it needs to match the actual: 210: deleter function's parameters, regardless of what template argument the: 211: last QSharedPointer instance had. Detailed Description. For example "sample: 45 2048". The problem is that this code is creating a QSharedPointer from a raw pointer, which implies ownership of the object pointed to.