无法移动 std::any

问题描述 投票:0回答:1

以下代码

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

无法编译,抱怨使用了

unique_ptr
的已删除复制构造函数。在模板参数中将
std::any
替换为
vptr
后,此代码可以编译,因此问题显然是
any

如何强制移动

std::any
而不是复制?

c++ c++17 move move-semantics stdany
1个回答
5
投票

问题不在于移动

std::any
,而是
std::any
本身不支持仅移动类型(例如
std::unique_ptr

根据cppreference

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

构造一个初始内容为

std::decay_t< ValueType>
类型的对象,从
std::forward< ValueType>(value)
直接初始化。 如果
std::is_copy_constructible< std::decay_t< ValueType>>::value
false
,则程序格式错误

您可以使用 static_assert 检查 is_copy_constructible ... 是否为 false,请参阅 coliru

我能想到的最简单的解决方法是使用shared_ptr,并仍然调用std::move。

© www.soinside.com 2019 - 2024. All rights reserved.