C++ (Qt)class Client{public: void draw() { if( !m_cache ) { m_cache = make_shared<DrawCache>(); forming( m_cache ); } paint( m_cache ); } private: shared_ptr<DrawCache> m_cache;};
C++ (Qt)typedef implicit_sharing<cache> shared_cache;typedef std::pair<shared_cache, shared_cache> pair_t; std::map<key, pair_t> map; shared_cache cacheA; map[keyA] = make_pair(cacheA, cacheA);...
C++ (Qt)#include <memory>#include <map>#include <iostream> using namespace std; struct DrawCache{ explicit DrawCache( int key2 ) : m_key2( key2 ) { cout << "Contruct DrawCache = " << m_key2 << endl; } ~DrawCache() { cout << "Destruct DrawCache = " << m_key2 << endl; } int m_key2;}; typedef shared_ptr<DrawCache> DrawCachePtr; class Client{public: explicit Client( int key2 ) { DrawCachePtr val = m_caches[ key2 ].lock(); if( !val ) { val = make_shared<DrawCache>( key2 ); m_caches[ key2 ] = val; } setCache( val ); } ~Client() { setCache( DrawCachePtr() ); } void changeCache( const Client &other ) { setCache( other.m_cache ); } void draw() { paint( m_cache ); } static void dumpCaches() { cout << "-----------------------------------------------------" << endl; for( const auto &entry : m_caches ) { DrawCachePtr cache = entry.second.lock(); cout << "Cache key2 = " << entry.first << " -> value = " << cache << endl; } } protected: void setCache( const DrawCachePtr &cache ) { // Если это последний указатель на данный кеш, удаляем его из справочника if( m_cache && m_cache.unique() ) m_caches.erase( m_cache->m_key2 ); m_cache = cache; } void paint( const DrawCachePtr &/*cache*/ ) { } private: DrawCachePtr m_cache; static map<int, weak_ptr<DrawCache>> m_caches;}; map<int, weak_ptr<DrawCache>> Client::m_caches; int main( int, char ** ){ { Client::dumpCaches(); Client cli1( 1 ); Client::dumpCaches(); Client cli2( 1 ); Client::dumpCaches(); Client cli3( 2 ); Client::dumpCaches(); cli2.changeCache( cli3 ); Client::dumpCaches(); cli1.changeCache( cli3 ); Client::dumpCaches(); } Client::dumpCaches(); return 0;}
C++ (Qt)std::map<Key1, Value *> map1;std::map<Key2, Value *> map2;