C++ “std::any_cast<;T>;`即使在要求使用指针时,也要求'T'是可构造的?

C++ “std::any_cast<;T>;`即使在要求使用指针时,也要求'T'是可构造的?,c++,c++17,std,C++,C++17,Std,我想std::any包含std::vector class-Foo{ 公众: Foo()=默认值; ~Foo()=默认值; Foo(const Foo&)=默认值; Foo(Foo&&)=默认值; Foo&运算符=(const Foo&)=默认值; Foo&operator=(Foo&&)=默认值; 虚拟空心条()=0; }; void f(){ 使用std::any; 使用std::任意_cast; 使用std::unique\u ptr; 使用std::vector; 使用V=向量; 任何a

我想
std::any
包含
std::vector

class-Foo{
公众:
Foo()=默认值;
~Foo()=默认值;
Foo(const Foo&)=默认值;
Foo(Foo&&)=默认值;
Foo&运算符=(const Foo&)=默认值;
Foo&operator=(Foo&&)=默认值;
虚拟空心条()=0;
};
void f(){
使用std::any;
使用std::任意_cast;
使用std::unique\u ptr;
使用std::vector;
使用V=向量;
任何a(V());
V*V=任何类型的铸件(&a);
}
根据,
std::any_cast(&a)
似乎返回
V*
。我认为这不会复制包含的对象。 但当我试图编译上述代码时,我得到了以下错误:

/usr/include/c++/8/bits/stl_construct.h:75:7: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Foo; _Dp = std::default_delete<Foo>]’
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/8/bits/stl_construct.h:75:7:错误:使用已删除的函数'std::unique\u ptr::unique\u ptr(const std::unique\u ptr&)[带_Tp=Foo;_Dp=std::default\u delete]'
{::新建(静态_-cast(u-p))_-T1(标准::转发(u-args));}
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这是否意味着
std::任何类型(&a)
都要求
V
是可构造的?
std::any_cast
是否复制所包含的对象,即使它只是被请求一个指针?如果是这样,为什么需要复制内容?

std::any
使用类型擦除技术。这意味着,无论对已擦除类型施加何种要求,都必须在擦除类型时检测到。这与模板类型不同,模板类型可以在调用实际使用这些需求的函数时评估需求

因此,即使你没有做真正需要它的事情,
any
仍然强加这些要求


话虽如此,在这种情况下,你正在做真正需要它的事情。即,
anya(V())。它会将对象复制到
a
的内部存储器中。请记住:您不能通过函数参数进行复制省略。

a
是一个函数,它接受
V
并返回
any
。如果您修复
a
-
anya(V{})
,您将注意到,您将得到一个没有任何抛出的错误。这是因为您在
any
中输入的任何内容都必须是可复制的。相关:@molbdnilo我误解了这个问题。我修复了声明并删除了调用
any_cast
的行,然后重新编译了代码,但仍然得到了相同的错误。所以我知道,任何演员都不是问题。@snbn这正是molbdnilo所指出的。问题不在于
任何\u cast
。问题是您不能将不可复制类型的对象(例如
std::vector
)放入
std::any
)中。编译时,无法确定
std::any
的内容是否可复制,因此
std::any
始终要求其内容可复制。是这样吗?