以下示例在Container container2(container1);
删除该行的情况下正确构建和运行。似乎std::variant
删除了自身的复制构造函数,这使得 myContainer
的复制构造函数被隐式删除。
实际上,我在问:
std::variant
将 a 存储为成员的正确方法是什么?Container
在允许安全复制/移动分配之前必须实施什么?
#include <string>
#include <variant>
class A {};
class Container {
public:
Container(int i) : data_(i) {}
Container(float f) : data_(f) {}
Container(std::string s) : data_(s) {}
Container(std::unique_ptr<A> a) : data_(std::move(a)) {}
std::variant<int, float, std::string, std::unique_ptr<A>> data_;
};
int main() {
Container container1{3};
// error: call to implicitly-deleted copy constructor of 'Container'
//
// copy constructor of 'Container' is implicitly deleted because
// field 'data_' has a deleted copy constructor
Container container2(container1);
return 0;
}