• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Boost.Flyweight example of use of key-value flyweights.
2  *
3  * Copyright 2006-2008 Joaquin M Lopez Munoz.
4  * Distributed under the Boost Software License, Version 1.0.
5  * (See accompanying file LICENSE_1_0.txt or copy at
6  * http://www.boost.org/LICENSE_1_0.txt)
7  *
8  * See http://www.boost.org/libs/flyweight for library home page.
9  */
10 
11 #include <boost/array.hpp>
12 #include <boost/flyweight.hpp>
13 #include <boost/flyweight/key_value.hpp>
14 #include <cstdlib>
15 #include <iostream>
16 #include <string>
17 #include <vector>
18 
19 using namespace boost::flyweights;
20 
21 /* A class simulating a texture resource loaded from file */
22 
23 class texture
24 {
25 public:
texture(const std::string & filename)26   texture(const std::string& filename):filename(filename)
27   {
28     std::cout<<"loaded "<<filename<<" file"<<std::endl;
29   }
30 
texture(const texture & x)31   texture(const texture& x):filename(x.filename)
32   {
33     std::cout<<"texture["<<filename<<"] copied"<<std::endl;
34   }
35 
~texture()36   ~texture()
37   {
38     std::cout<<"unloaded "<<filename<<std::endl;
39   }
40 
get_filename() const41   const std::string& get_filename()const{return filename;}
42 
43   // rest of the interface
44 
45 private:
46   std::string filename;
47 };
48 
49 /* key extractor of filename strings from textures */
50 
51 struct texture_filename_extractor
52 {
operator ()texture_filename_extractor53   const std::string& operator()(const texture& x)const
54   {
55     return x.get_filename();
56   }
57 };
58 
59 /* texture flyweight */
60 
61 typedef flyweight<
62   key_value<std::string,texture,texture_filename_extractor>
63 > texture_flyweight;
64 
main()65 int main()
66 {
67   /* texture filenames */
68 
69   const char* texture_filenames[]={
70     "grass.texture","sand.texture","water.texture","wood.texture",
71     "granite.texture","cotton.texture","concrete.texture","carpet.texture"
72   };
73   const int num_texture_filenames=
74     sizeof(texture_filenames)/sizeof(texture_filenames[0]);
75 
76   /* create a massive vector of textures */
77 
78   std::cout<<"creating flyweights...\n"<<std::endl;
79 
80   std::vector<texture_flyweight> textures;
81   for(int i=0;i<50000;++i){
82     textures.push_back(
83       texture_flyweight(texture_filenames[std::rand()%num_texture_filenames]));
84   }
85 
86   /* Just for the sake of making use of the key extractor,
87    * assign some flyweights with texture objects rather than strings.
88    */
89 
90   for(int j=0;j<50000;++j){
91     textures.push_back(
92       texture_flyweight(
93         textures[std::rand()%textures.size()].get()));
94   }
95 
96   std::cout<<"\n"<<textures.size()<<" flyweights created\n"<<std::endl;
97 
98   return 0;
99 }
100