Объекты типаflyweight<...>обеспечивают доступ к неизменяемым значениям типаflyweight<...>::value_type, со следующими преимуществами по сравнению с простымvalue_typeОбъекты:
Объекта (субстанция) - субстанция (субстанция) (связьзначение_тип).
мускулатуры по вопросам, касающимся суррогатной материнстваразмера (value_type)
Таким образом, если уровень избыточности (отношение общих объектов к различным значениям) достаточно высок, заменив подходящую инстанциациюмухоловкиназначение_типприводит к сокращению использования памяти.Объекты с эквивалентным значением имеют одинаковое представление (связанныйvalue_typeобъект).
Размер мухоловок обычно равен размеру указателя, который в целом меньшеsizeof(value_type).
So, if the level of redundancy (ratio of total objects to different values)
is high enough, substituting a suitable instantiation of flyweight
for value_type results in a reduction in memory usage.
[ORIG_END] -->
Flyweightпараметризируется в соответствии с некоторыми аспектами:
Эти аспекты влияют на внутреннюю структуру и поведениемухоловкиследующим образом:
ü ulхолакамухоловкии вертикали УКП и вертикали УКВПмута, а также регулировщика УКВ.
На фабрике полулегкоместа грузоподъемности грузоподъемностиВход, на складе с обратной связьюconst key_type&, а на складеvalue_type.значение_типВходВход[скрыто] [скрыто] [скрыто] [скрыто] [скрыто]].
Связанный с ним джекпот мутекса с материалом в материале и депонированном материале.
Далее мы неявно предполагаем, что эквивалентностьтипа ключаотносится к эквивалентности, вызванной используемым классом фабрики. Кроме того, два значенияvalue_typeсчитаются эквивалентными, если они построены из эквивалентных ключей или являются копиями объектов, построенных из эквивалентных ключей.Типыkey_valueиvalue_type(возможно, равные), гдеkey_typeслужит ключевым типом для поиска и построения внутренних общих экземпляров объектовvalue_type.
Факультативныйтегтип, предназначенный для синтаксически дифференцировать между иными идентичными инстанциациями.
Заводской классиспользовался для хранения и извлечения объектов общей ценности.
Тип держателяиспользуется для создания фабрики и объекта mutex, которые являются уникальными для каждой специализации шаблона классаflyweight.
политика блокировки, определяющая механизмы синхронизации для внутреннего доступа к общим ресурсам.
политика отслеживания, которая контролирует, как обрабатываются значения, когда все связанные с ними объекты с массой тела уничтожаются.
These aspects impact the internal structure and behavior
of the flyweight instantiation in the following manner:
Каждая инстанцияflyweightвнутренне владеет уникальным фабричным объектом и уникальным объектом синхронизацииmutex, оба из которых создаются с использованием ассоциированного типа держателя.
На фабрике в полулегком весе хранятся элементы нераскрытого типаEntry, которые неявно конвертируются вconst key_type&, а также хранится подобъектvalue_type. Каждый весовой объект связан с подобъектомvalue_typeизEntry, хранящимся на заводе.
Связанный объект mutex используется для защиты всех обращений к функциям вставки и удаления внутренней фабрики.
Каждый объект с массой тела внутри хранит значение некоторого нераскрытого типаHandle.Handleи упомянутый выше типEntryполучены из вызовов к соответствующей политике отслеживания способом, описанным для этой концепции.
In what follows, we implicitly assume that key_type equivalence
refers to the equivalence relationship induced by the factory class used.
Also, two values of value_type are considered equivalent
if they are constructed from equivalent keys, or are copies of
objects constructed from equivalent keys.
[ORIG_END] -->
#include<initializer_list>template<typenameT,typenameArg1,typenameArg2,typenameArg3,typenameArg4,typenameArg5>classflyweight{public:typedefdependent on Tkey_type;typedefdependent on Tvalue_type;// static data initialization:staticboolinit();classinitializer{public:initializer();};// construct/copy/destroy:flyweight();template<typename...Args>explicitflyweight(Args&&...args);template<typenameV>flyweight(std::initializer_list<V>list);flyweight(constflyweight&x);flyweight(flyweight&x);flyweight(constflyweight&&x);flyweight(flyweight&&x);explicitflyweight(constvalue_type&x);explicitflyweight(value_type&x);explicitflyweight(constvalue_type&&x);explicitflyweight(value_type&&x);template<typenameV>flyweight&operator=(std::initializer_list<V>list);flyweight&operator=(constflyweight&x);flyweight&operator=(constvalue_type&x);flyweight&operator=(value_type&&x);// convertibility to underlying type:constkey_type&get_key()const;constvalue_type&get()const;operatorconstvalue_type&()const;// modifiers:voidswap(flyweight&x);};
В первом случае вложенные типыkey_typeиvalue_typeравныT. Во втором случаеkey_type=Key,value_type=Value; тогда мы говорим, что инстанциацияflyweightявляетсяkey-valueflyweight.value_type- это тип значений, к которым дают доступ объекты с массой тела, в то время как поиск значений основан на соответствующих значенияхkey_type.ключевое значениедолжно бытьПризнаваемоеизначение_типдолжно быть сконструировано изключ_тип; кроме того,ключевое значениедолжно соответствовать любым дополнительным требованиям, предъявляемым к типу используемого завода. Для мухоловок с ключевым значением гарантируется, что создание или присвоение мухоловочного объекта приводит не более чем к одной конструкции (или копированию конструкции в некоторых конкретных случаях) объектазначения_типа, и эта конструкция происходит только в том случае, если ранее на мухоловочном заводе не существовало эквивалентного значения.произвольного типа,
In the first case, the nested types key_type and value_type
are both equal to T. In the second case, key_type=Key,
value_type=Value; we say then that the instantiation
of flyweight is a key-value flyweight.
value_type is the type of the values flyweight objects give access to,
while value lookup is based on associated key_type values.
key_value must be
Assignable
and value_type must be constructible from key_type;
additionally, key_value must
conform to any extra requirements imposed by the type of factory used.
For key-value flyweights, it is guaranteed that the creation or assignment of a flyweight
object results in at most one construction (or copy construction in some
particular cases) of an object
of value_type, and this construction only occurs in the case that no
equivalent value existed previously in the flyweight factory.
[ORIG_END] -->
ТипыArg1, ...,Arg5, если они предусмотрены, должны быть любыми из следующих, без особого порядка:
А,
, [скрыто], [скрыто].
Трубопроводящий стабилизатор,
- блокирование,
.
Ни один аспект не может быть указан дважды. Каждая внутренняя составляющаямуфтыполучена с помощью соответствующего спецификатора; например, фабрика является результатом определенного (MPL) вызова данного заводского спецификатора, внутреннего мутекса из данной политики блокировки и т.д. Аргументы конфигурации по умолчанию:
No aspect can be specified twice. Each internal component of the
flyweight instantiation is obtained through use of the
corresponding specifier; for instance, the factory results from a
certain (MPL) invocation of the given factory specifier, the internal
mutex from the given locking policy, etc.
The default configuration arguments are:
Статические данные, внутренние для данногомухоловкиинстанциации (заводской экземпляр и т.д.) построены во время фазы динамической инициализации программы и всегда перед первым общепрограммным использованием инстанциированного класса. Следующие утилиты могут быть использованы, когда требуется больше контроля над моментом строительства.
static bool init();
Effects: After execution of this function the static data associated
to the instantiation of flyweight is guaranteed to be
constructed. Note: Concurrent execution of this function is not thread safe.
Effects: Constructs a flyweight object with the value
value_type(key_type(std::forward<Args>(args)...))
if flyweight is key-value
or value_type(std::forward<Args>(args)...)
otherwise. Note: In compilers without variadic template support, the implementation
replaces this constructor with a number of overloads accepting
any combination of const/non-const lvalue/rvalue reference arguments
up to a maximum number that
can be globally configured by the user.
Effects: Constructs a flyweight object with the value
value_type(key_type(list)) if flyweight is key-value
or value_type(list) otherwise. Note: The specialization for a particular std::initializer_list<V'>
of this member function template is not available unless
key_type is constructible from
std::initializer_list<V'>.
Requires: If flyweight is key-value,
value_type is
Assignable
and the
Key ExtractorKeyFromValue must have been supplied as part of the
key_value<> construct. Effects: Constructs a flyweight associated to a
copy of x or with a value_type constructed
from a key equivalent to that associated to x. For non-key-value
flyweights, x is its own key; for key-value flyweights,
the key is extracted through use of an object of type KeyFromValue.
Effects:*this=flyweight(list). Returns:*this. Note: The specialization for a particular std::initializer_list<V'>
of this member function template is not available unless
key_type is constructible from
std::initializer_list<V'>.
flyweight& operator=(const flyweight& x);
Effects: Associates the flyweight object with the same value
as x. Returns:*this. Exception safety:nothrow.
Returns: A copy of the key used to construct the
value_type associated to the flyweight
object. Exception safety: If flyweight is not key-value or
if KeyFromValue was not provided, nothrow.
Effects: Swaps the associations to value_types each
flyweight object has. No swapping of key_type or
value_type objects is done. Exception safety:nothrow.
Returns: If x and y are of the same type, returns
true if and only if they are associated to the same value; if
x and y have different types, returns
x.get()==y.get(). Exception safety: If x and y are of the same type,
nothrow.
Requires: If flyweight is key-value,
value_type is
Assignable
and the
Key ExtractorKeyFromValue must have been supplied as part of the
key_value<> construct. Effects: Reads an object of type value_type from in
and assigns it to x. Returns:in.
Поддерживается хешированиепри весекак сstd::hash, так ибустером::hash. В любом случае вычисление не включает в себя хеширование самих объектов, связанных сзначением_типом; поэтому не имеет значения, является лизначение_типомхешируемым или нет. Результаты, полученные с помощьюstd::hashиboost::hashдля одного и того жеобъекта, обычно отличаются. Примечание:Поддержка хэша может быть отключенадля решения столкновений с кодом, где это уже определено пользователем.
This template specialization meets the requirements of class template std::hash in [unord.hash].
No exception is thrown when invoking instances of this specialization.
In compilers without variadic template support,
globally define this macro to set the maximum number of
arguments accepted by flyweightforwarding constructor, which by default
is 5.
If defined, hash support is not provided. This can be useful to cope
with legacy code where general flyweight hashing has already been
defined by the user.
Flyweights можно архивировать и извлекать с помощьюBoost.Serialization. Поддерживаются как обычные, так и XML архивы. Сериализация выполняется эффективным образом, так что экономия эквивалентноговесаприводит к тому, что их общее значениеkey_typeсохраняется только один раз, независимо от того, отслеживается лиkey_typeBoost.Serialization или нет.
Operation: saving of a flyweight object x to an
output archive (XML archive) ar.
Requires:key_type is serializable (XML-serializable). Effects: The value k=x.get_key() is saved into ar as
part of this operation or of a previous saving operation of a flyweight
object with the same key. Exception safety: Strong with respect to x. If an exception
is thrown, ar may be left in an inconsistent state.
Operation: loading of a flyweightx' from an
input archive (XML archive) ar.
Requires:key_type is serializable (XML-serializable). Effects:x' is associated to a value constructed from a key
equivalent to k', a restored copy of the value k
defined above. Exception safety: Strong with respect to x'. If an exception
is thrown, ar may be left in an inconsistent state.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.