While implementing C++17's std::any
according to the specification available in this Wiki I stumbled across something that seemed nonsensical to me:
In the definition of the free function std::any_cast
, which is used to retrieve values from an std::any
instance, an overload for r-value references is supplied (It's the third one):
template< class ValueType >
ValueType any_cast(any&& operand); // (3)
Now, there is a requirement listed below the synopsis that applies to overloads 2 and 3 (that means also including the r-value overload):
2-3)
Returns*any_cast<std::remove_reference_t<ValueType>>(&operand)
The definition does not seem to actually allow moving the data!
The function call is just redirected to the pointer-based overload; the information about the temporary nature of operand
is lost!
Is it intended that I can't move out of an any instance? Is it just a error in the wiki? Am I wrong here?
Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any .
std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.
std::move. std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.
Defined in header <any> class any; (since C++17) The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.
The issue is in WP status at the time of writing this, which means:
WP - (Working Paper) - The proposed resolution has not been accepted as a Technical Corrigendum, but the full WG21/PL22.16 committee has voted to apply the Defect Report's Proposed Resolution to the working paper.
See the lwg here for more info: http://wg21.cmeerw.net/lwg/issue2509
A proposed resolution is indeed
For the third form, if
is_move_constructible_v<ValueType>
is true andis_lvalue_reference_v<ValueType>
is false,std::move(*any_cast<remove_reference_t<ValueType>>(&operand))
, otherwise,*any_cast<remove_reference_t<ValueType>>(&operand)
And the defect report list listing the WP: http://cplusplus.github.io/LWG/lwg-defects.html#2509
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With