简体   繁体   English

std :: optional中不可复制的容器

[英]container of non-copyable in std::optional

I'm trying to pack a (STL-)container of non-copyable type into an std::optional, eg: 我正在尝试将一个不可复制类型的(STL-)容器打包到std :: optional中,例如:

class MyClass
{
    MyClass(const MyClass&) = delete;
};
std::optional<std::list<MyClass>> optContainer;

But the compiler (GCC 7.2) complains 但是编译器(GCC 7.2)抱怨道

error: use of deleted function 'MyClass::MyClass(const MyClass&)' { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); 错误:使用已删除的函数'MyClass :: MyClass(const MyClass&)'{:: new((void *)__ p)_Up(std :: forward <_Args>(__ args)...); } }
[...] note: declared here [...]注意:在这里宣布
MyClass(const MyClass&) = delete; MyClass(const MyClass&)=删除;

and presents a deep "required from ..." stack going into type_traits (and more) where it checks for std::is_trivially_copy_constructible on the std::list. 并提供一个深入的“required from ...”堆栈进入type_traits(以及更多),它在std :: list上检查std :: is_trivially_copy_constructible。 I suspect that there the compiler finds the container (std::list in the example) to be trivially copy constructible but does not check the value type of the container for trivial constructability and then goes the wrong path. 我怀疑编译器发现容器(示例中的std :: list)可以简单地复制可构造但不检查容器的值类型是否具有普通的可构造性,然后走错了路径。

Of course the non-copyable type (not in a container) in an std::optional works: 当然std :: optional中的不可复制类型(不在容器中)起作用:

std::optional<MyClass> optValue; // ok

I know that I can work around that eg like so: 我知道我可以解决这个问题,例如:

template<typename T>
class CNonCopyable : public T
{
public:
    template<typename... Params>
    CNonCopyable(Params&&... params)
        : T(std::forward<Params>(params)...)
    {}
    CNonCopyable(const CNonCopyable&) = delete;
    CNonCopyable(CNonCopyable&&) = default;
    virtual ~CNonCopyable() = default;
    CNonCopyable& operator=(const CNonCopyable&) = default;
    CNonCopyable& operator=(CNonCopyable&&) = default;
};
std::optional<CNonCopyable<std::list<MyClass>>> optContainer;

But I wonder if there is a better way without the CNonCopyable class. 但我想知道没有CNonCopyable类是否有更好的方法。

(Just as an example where no own type is involved:) Same occurs when trying to pack a container of std::unique_ptr into an std::optional, because std::unique_ptr is not copy constructible: (就像没有涉及自己的类型的例子一样)当尝试将std :: unique_ptr的容器打包到std :: optional中时会发生同样的情况,因为std :: unique_ptr不是可复制构造的:

std::optional<std::list<std::unique_ptr<int>>> optContainer;

This was a bug in GCC that has since been patched. 这是GCC中的一个错误,此后已被修补。

See 81190 and 80654 8119080654

Use a newer version of GCC (eg, 8) and you will not encounter the issue. 使用较新版本的GCC(例如,8),您将不会遇到此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM