Sometimes it is necessary to adjust the default registration behaviour of RTTR. Therefore policies were introduced. There are policies for constructors, methods and properties available.
- as_object
- as_std_shared_ptr
- as_raw_ptr
- bind_as_ptr
- return_ref_as_ptr
- discard_return
For easier usage, the policies are grouped to its corresponding items; e.g. all policies for methods can be found under policy::meth
; all policies for properties under policy::prop
etc.
Constructors
as_object
The as_object policy will create an instance of a class with automatic storage.
Objects with automatic storage duration are automatically destroyed when the block in which they are created exits. Which is in our case the variant. However, that means also you don't have to deal with pointers or wrappers. In order to use this creation policy, the object must be copy constructible.
See following example code:
as_std_shared_ptr
The as_std_shared_ptr policy will create an instance of a class through std::make_shared<T>.
That means the object is wrapped into a std::shared_ptr<T>. The wrapped object is destroyed and its memory deallocated when either of the following happens:
- the last remaining variant object (which contains the shared_ptr owning the object is destroyed.
- the last remaining variant owning the shared_ptr is assigned another object.
The object is destroyed using the default deleter of std::shared_ptr.
See following example code:
as_raw_ptr
The as_raw_ptr policy will create an instance of a class as raw pointer.
That means the object is created with a new-expression and its lifetime lasts until it is destroyed using a delete-expression. In order to invoke the delete expression use the corresponding destructor.
See following example code:
Properties
bind_as_ptr
The motivation for this policy is to avoid expensive copies when returning a property. The default registration behaviour of RTTR is to return all values by copying the content in a variant. When you have primitive data types like integer or doubles you are good to go with the standard binding behaviour. But when you have big arrays, it would be a waste to always copy the content when retrieving or setting the value, therefore this policy was introduced.
Example:
return_ref_as_ptr
The motivation for this policy is the same like the bind_property_as_ptr policy. When you really need to get a reference to the return value of a method call you have to use this policy, otherwise the returned reference will be copied into the variant.
Example:
Methods
discard_return
Sometimes it is necessary that the client caller should ignore the return value of a method call. Therefore this policies was introduced.
Example:
A closing hint: you can of course build your own policies in that way, that you build wrappers around your properties or methods and then bind the wrapper instead of the original accessor.