C++ (Qt)#include <iostream>#include <memory> class trigger{public: trigger() : m_flag(true) {} bool get() const { return m_flag; } friend class trackable; private: void set(bool flag) { m_flag = flag; } bool m_flag;}; typedef std::shared_ptr<trigger> spy_type; class trackable{public: trackable(const trackable &) : spy(std::make_shared<trigger>()) {} trackable() : spy(std::make_shared<trigger>()) {} trackable &operator=(const trackable &) { return *this; } ~trackable() { spy->set(false); } spy_type spy;}; struct SomeObject : public trackable{ //...}; struct SomeClient{ SomeObject * m_Object; bool objectIsValid() const { return (spy) ? spy->get() : false; } void setObject(SomeObject * obj) { m_Object = obj; spy = obj->spy; } private: spy_type spy;}; int main(){ SomeClient Client; std::cout << std::boolalpha << Client.objectIsValid() << std::endl; SomeObject * Object = new SomeObject(); Client.setObject(Object); std::cout << Client.objectIsValid() << std::endl; delete Object; std::cout << Client.objectIsValid() << std::endl; return 0;}
C++ (Qt)QWeakPointer<SomeObject> m_Object;
C++ (Qt)QPointer<SomeObject> m_Object;
auto parent = std::make_unique<QMainWindow>();std::observer_ptr<QWidget> w1 = QObject::makeChild<QWidget>(parent);auto w2 = std::make_unique<QWidget>();w1->addChild(std::move(w2));
QAbstractItemModel *QAbstractItemView::model() const
QGraphicsRectItem *QGraphicsScene::addRect()
void QDataStream::setDevice(QIODevice *d)
std::observer_ptr<QIODevice> QDataStream::device(d) const;void QDataStream::setDevice(std::observer_ptr<QIODevice> d);
C++ (Qt)CSomeObject * refTarget; // на него ссылаемсяCAnotherObject * refНandle; // а этот ссылается на кого-то ... // устанавливаем связь между объектамиСReferenceManager::InstallLink(refTarget, refHandle, LINK_TYPE_DEFAULT);..// имея target перебираем ссылающихся int numLinks = СReferenceManager::GetHandleCount(refTarget); // вернет 1 (один объект ссылается)int linkType, index = 0;void * handle = СReferenceManager::GetIndexedHandle(refTarget, index, &linkType);void * handle2 = СReferenceManager::GetTypedHandle(refTarget, LINK_TYPE_DEFAULT);...// имея ссылающегося извлекаем targetvoid * target = СReferenceManager::GetTarget(refНаndle, LINK_TYPE_DEFAULT);
C++ (Qt)#include <iostream>#include <list> class Object{ //...}; class Client{public: Object * m_Object; void makeUndo() { // ... m_Object = nullptr; }}; class Manager{public: Manager(Object * obj = nullptr) : m_object(obj) {} void addClient(Client * client) { m_subscribers.push_back(client); } void killObject() { for (auto c : m_subscribers) c->makeUndo(); delete m_object; m_object = nullptr; } private: Object * m_object; std::list<Client*> m_subscribers;}; int main(){ Object * obj = new Object; Client client1; Client client2; client1.m_Object = obj; client2.m_Object = obj; Manager manager(obj); manager.addClient(&client1); manager.addClient(&client2); manager.killObject(); return 0;}