你好stack overflowers,我有一个设计使用flyweight模式来共享位图,这些位图在管理绘图操作等的位图对象之间共享,并集成到gui库中。这是一款嵌入式设备,因此内存非常宝贵。目前我已经完成了一个工作实现,其中有一个 std::vector of auto_ptr 的 light 类,它计算使用情况。我知道这是个坏主意,可能会泄露,所以我正在重写这部分。我正在考虑使用 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 ;
}
关于c++ - 使用享元模式在位图对象之间共享位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496930/