我有一个包含 unique_ptr 的对象,因此如果不进行深度复制(我不想要)就无法进行复制构造。
我想让 std::any 持有那个对象,但我发现的唯一替代方法是让 std::any 持有一个指针,这会增加一个无用的间接寻址,或者让我的对象有一个唯一的指针。下面的代码有望说明我的观点:
//Compiled with clang++ -std=c++2a; clang version 5.0.0
#include <iostream>
#include <any>
#include <memory>
struct A {
std::unique_ptr<int> m = std::make_unique<int>(11);
A(A&& a): m(std::move(a.m)) {}
A() {}
};
struct B {
std::shared_ptr<int> m = std::make_shared<int>(11);
};
template<class T>
void use_any_ptr() {
std::any a{new T{}};
std::cout << *(std::any_cast<T*>(a)->m) << std::endl;
}
template<class T>
void use_any() {
std::any a{T{}};
std::cout << *(std::any_cast<T>(a).m) << std::endl;
}
int main() {
use_any_ptr<A>(); // Workaround using a pointer
use_any<B>(); // Workaround using shared pointer
use_any<A>(); // Breaks because A has no cc no matching constructor for initialization of 'std::any'
}
据我了解,std::any 的构造似乎需要复制对象,但我不确定为什么不能简单地移动对象。
有没有办法解决这个问题?也就是说,除了使用 shared_ptr 之外,这意味着我基本上是为了创建 any 对象或传递 std::any 指针而表达“错误的东西”(这是一个不需要的间接级别,因为 std::据我所知,any 持有一个指向类型的 void 指针)。
是否有任何可以在创建时使用 move ctr 而不是 copy ctr 的不同实现?
还是我太傻了,没有理解这里的“真正”问题?
最佳答案
Or am I being silly and not understanding the "real" problem here ?
这里的问题很简单:std::any
有a copy constructor因此它要求包含的对象是可复制构造的。
解决这个问题的方法是定义一个包含指针的自定义对象,该对象是可复制的,并且为其实现正确逻辑(无论正确是什么意思在你的情况下,我看不出你如何复制一个 std::any
并因此包含一个拥有 std::unique_ptr
的对象,但也许你可以在你的情况下以某种方式摆脱它)。
否则请重新考虑您的设计并尝试摆脱对 std::any
的需求。它确实没有太多用处,也许你可以通过一些模板机制或 std::variant
或其他任何东西来获得相同的效果
关于c++ - std::any 用于不能复制构造的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46852168/