您好堆栈溢出程序,我有一个使用flyweight模式来共享位图的设计,这些位图在管理绘图操作等的位图对象之间共享,并集成在gui库中。这是一个嵌入式设备,因此内存非常宝贵。目前,我已经完成了一个轻量级的auto_ptr的std::vector的可行实现,该计数可以计算使用量。我知道这是个坏主意,可能会泄漏,因此我将重写此部分。我正在考虑使用boost::shared_ptr。我的问题的关键是,如果不使用,我希望释放的位图。如果我有一个shared_ptr池,则最终将使用的位图加载一次。如果使用use_count()== 1,我正在考虑使用shared_ptr::use_count()删除位图。但是该文档警告use_count()的生产代码。基本上,问题是飞重模式会释放单个重物。您认为有更好的方法吗?

最佳答案

您可以使用 boost 弱指针池,以便该池不计入所有权。

只有位图对象具有 boost 的共享指针,这样它们才可以决定何时释放位图。

弱指针池使我们能够检索已经构造的位图:

创建位图对象时,您可以:

  • 如果不为空,则从弱指针获取共享指针
  • 或以其他方式加载新的位图,从中创建新的共享指针,然后在池中插入/替换弱指针。

  • 以下是一些使用池图的示例代码:
    #include <boost/shared_ptr.hpp>
    #include <boost/weak_ptr.hpp>
    #include <map>
    #include <string>
    #include <iostream>
    
    // represents the bitmap data
    class Bitmap
    {
    public :
        Bitmap( std::string const& name ) : name( name )
        {
            std::cout << "Bitmap " << name << std::endl ;
        }
    
        ~Bitmap()
        {
            std::cout << "~Bitmap " << name << std::endl ;
        }
    
        std::string name ;
    };
    
    // the flyweight pool
    class Factory
    {
    public :
    
        typedef std::map< std::string , boost::weak_ptr< Bitmap > > Map ;
    
        boost::shared_ptr< Bitmap > get( std::string const& what )
        {
            Map::iterator x = map.find( what );
    
            // retrieve existing object from map's weak pointers
    
            if( x != map.end() )
            {
                if( boost::shared_ptr< Bitmap > shared = x->second.lock() )
                {
                    return shared ;
                }
            }
    
            // populate or update the map
    
            boost::shared_ptr< Bitmap > shared( new Bitmap( what ) );
            boost::weak_ptr< Bitmap > weak( shared );
            map.insert( std::make_pair( what , weak ) );
            return shared ;
        }
    
    private :
        Map map ;
    };
    
    
    int main(int argc, char** argv)
    {
        Factory f ;
    
        // we try our flyweight bitmap factory ...
    
        boost::shared_ptr< Bitmap > a = f.get( "a" );
        boost::shared_ptr< Bitmap > b = f.get( "b" );
    
        // a is not made again
        boost::shared_ptr< Bitmap > a2 = f.get( "a" );
    
        a.reset();
        a2.reset();
    
        // a is destroyed before ------
    
        std::cout << "------" << std::endl ;
    }
    

    09-16 05:10
    查看更多