小编Yan*_*hao的帖子

删除基类中的移动构造函数不会阻止从函数返回派生类对象

给定基类 A 和派生类 B,A 删除了移动构造函数:

class A {
public: 
  A()  {}
  A(const A&) = default;
  A(A&&) = delete; 
};

class B : public A
{ 
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于删除了移动构造函数,以下函数无法编译:

A f() {
  A a;
  return a;
}
Run Code Online (Sandbox Code Playgroud)

但 B 的类似函数不会报告任何错误:

B g() {
  B b;
  return b;
}
Run Code Online (Sandbox Code Playgroud)

这是否意味着B中的移动构造函数没有被删除?我想知道标准中的规则是什么。

c++ inheritance constructor move-semantics

19
推荐指数
2
解决办法
1647
查看次数

移动 unique_ptr:重置源 vs. 销毁旧对象

我的问题是关于https://en.cppreference.com/w/cpp/memory/unique_ptr中的示例

struct List
{
    struct Node
    {
        int data;
        std::unique_ptr<Node> next;
    };
 
    std::unique_ptr<Node> head;
 
    ~List()
    {
        // destroy list nodes sequentially in a loop, the default destructor
        // would have invoked its `next`'s destructor recursively, which would
        // cause stack overflow for sufficiently large lists.
        while (head)
            head = std::move(head->next);
    }
 
    ...
};
Run Code Online (Sandbox Code Playgroud)

当 时head = std::move(head->next),会发生三件事:

  1. 重置head->nextnullptr
  2. 设置head为新值;
  3. head销毁曾经指向的Node 对象;

上面的代码有效意味着 3 保证在 1 之后发生,否则链接仍然存在。

我想知道是否有一个书面规则来保证这样的顺序,或者它只是一个隐藏的实现细节,并且该示例可以正常工作。

c++ move unique-ptr

8
推荐指数
1
解决办法
281
查看次数