Value const-ness and shared_vector¶
- page vectorconst
The type ‘shared_vector<T>’ can be thought of as ‘T*’. Like the T pointer there are three related constant types:
shared_vector<int> v_mutable; // 1 const shared_vector<int> v_const_ref; // 2 shared_vector<const int> v_const_data; // 3 const shared_vector<const int> v_const_ref_data; // 4
The distinction between these types is what “part” of the type is constant, the “reference” (pointer) or the “value” (location being pointed to).
Type #2 is constant reference to a mutable value. Type #3 is a mutable reference to a constant value. Type #4 is a constant reference to a constant value.
Casting between const and non-const values does not follow the normal C++ casting rules (no implicit cast).
For casting between shared_vector<T> and shared_vector<const T> explicit casting operations are required. These operations are freeze() (non-const to const) and thaw() (const to non-const).
A ‘shared_vector<const T>’ is “frozen” as its value can not be modified. However it can still be sliced because the reference is not const.
These functions are defined like:
namespace epics{namespace pvData{ template<typename T> shared_vector<const T> freeze(shared_vector<T>&); template<typename T> shared_vector<T> thaw(shared_vector<const T>&); }}
So each consumes a shared_vector with a certain value const-ness, and returns one with the other.
The following guarantees are provided by both functions:
The returned reference points to a value which is equal to the value referenced
by the argument. The returned reference points to a value which is only referenced by
shared_vectors with the same value const-ness as the returned reference.
Freezing¶
The act of freezing a shared_vector requires that the shared_vector passed in must be unique() or an exception is thrown. No copy is made.
The possibility of an exception can be avoided by calling the make_unique() on a shared_vector before passing it to freeze(). This will make a copy if necessary.
Thawing¶
The act of thawing a shared_vector may make a copy of the value referenced by its argument if this reference is not unique().
Note
The argument of both freeze() and thaw() is a non-const reference which will always be cleared.