Cannot move std::any
Asked Answered
P

1

1

The following code

using vptr = std::vector<std::unique_ptr<int>>;
auto m = std::unordered_map<int, std::any>{};
m.try_emplace(0, move(vptr{}));

Fails to compile, complaining about using of deleted copy constructor of unique_ptr. After replacing std::any with vptr in template argument this code compiles, so the issue is clearly with any

How can I force std::any to be moved instead of copied?

Pentacle answered 29/5, 2019 at 22:12 Comment(1)
Note that you don't need to do move(vptr{}), vptr{} is already an rvalue.Ambsace
B
5

The problem is not moving std::any, it's that std::any itself does not support move-only types (std::unique_ptr for example)

as per cppreference

template< class ValueType >
any( ValueType&& value );

Constructs an object with initial content an object of type std::decay_t< ValueType>, direct-initialized from std::forward< ValueType>(value). If std::is_copy_constructible< std::decay_t< ValueType>>::value is false, the program is ill-formed

You can check that is_copy_constructible ... is false with a static_assert, see on coliru

Easiest workaround I can think of is to use shared_ptr instead and still call the std::move.

Breton answered 29/5, 2019 at 23:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.