无法移动std :: any [英] Cannot move std::any

查看:121
本文介绍了无法移动std :: any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

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

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

如何强制移动std::any而不是复制?

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

推荐答案

问题不是移动std :: any,这是因为std :: any本身不支持仅移动类型(例如std :: unique_ptr)

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

按照 cppreference

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

使用初始内容构造一个对象,该对象的类型为直接从std::forward< ValueType>(value)初始化的std::decay_t< ValueType>类型的对象. 如果std::is_copy_constructible< std::decay_t< ValueType>>::valuefalse,则表明程序格式错误

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

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

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

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

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

这篇关于无法移动std :: any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆