I want to std::any
to contain std::vector<std::unique_ptr<T>>
.
class Foo {
public:
Foo() = default;
~Foo() = default;
Foo(const Foo&) = default;
Foo(Foo&&) = default;
Foo& operator=(const Foo&) = default;
Foo& operator=(Foo&&) = default;
virtual void bar() = 0;
};
void f() {
using std::any;
using std::any_cast;
using std::unique_ptr;
using std::vector;
using V = vector<unique_ptr<Foo>>;
any a(V());
V* v = any_cast<V>(&a);
}
According to the document, std::any_cast<T>(&a)
seems to return V*
. I think this doesn't copy the contained object.
But when I tried to compile the above code, I got the following error:
/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)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Does it means that std::any_cast<V>(&a)
requires V
to be constructible? Does std::any_cast
copy the contained object even when it is simply asked for a pointer? If so, why does it need to copy the content?