Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++17's std::any not allow returning a movable value by any_cast?

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?

like image 531
nshct Avatar asked Jul 25 '16 16:07

nshct


People also ask

Does std :: Any require RTTI?

Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any .

Does STD copy move?

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.

What does std :: move do?

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.

What is std any?

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.


Video Answer


1 Answers

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 and is_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

like image 69
Marco A. Avatar answered Oct 10 '22 00:10

Marco A.