孙子的副本构造函数导致孙父母的std :: optional成员的默认赋值运算符被删除

时间:2019-05-09 20:55:24

标签: c++

我不明白为什么在下面的代码中,复制构造函数导致std :: optional的复制赋值运算符被删除?如果您注释掉复制构造函数,则可以正常编译。

我需要GrandChild的副本构造函数,并且我希望这些成员保持可选状态。

clang++ -std=c++17 test.cpp
#include <optional>
#include <string>

class GrandChild {
public:
    GrandChild() { }

    GrandChild(GrandChild& other) { }; // Comment out this line and it works???
};

class Child
{
public:
    std::optional<GrandChild> child;

    explicit Child() { }

    Child(Child& other) {};
};

class Parent
{
public:
    std::optional<Child> child;

    Parent() {}
};

int main() 
{
    Parent parent;
    Child child;
    parent.child = child; // object of type 'std::__1::optional<Child>' cannot be assigned because its copy assignment operator is implicitly deleted
}
test.cpp:34:18: error: object of type 'std::__1::optional<Child>' cannot be assigned
      because its copy assignment operator is implicitly deleted
    parent.child = child; // object of type 'std::__1::optional<Child>' cannot ...
                 ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/optional:757:41: note:
      explicitly defaulted function was implicitly deleted here
    _LIBCPP_INLINE_VISIBILITY optional& operator=(const optional&) = default;
                                        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/optional:583:7: note: copy
      assignment operator of 'optional<Child>' is implicitly deleted because base class
      '__optional_sfinae_assign_base_t<Child>' (aka
      'std::__1::__sfinae_assign_base<false, false>') has a deleted copy assignment
      operator
    , private __optional_sfinae_assign_base_t<_Tp>
      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/__tuple:533:25: note:
      'operator=' has been explicitly marked deleted here
  __sfinae_assign_base& operator=(__sfinae_assign_base const&) = delete;

0 个答案:

没有答案