【问题标题】:May I call destructor from move assignement operator?我可以从移动赋值运算符调用析构函数吗?
【发布时间】:2020-04-10 00:26:52
【问题描述】:

好吧,我的班级中有重要的析构函数。

我可以这样做吗:

Foo& Foo::operator=(Foo&& from) {
    ~Foo()
    // Copy the stuff and cleanup "from"
}

我想要实现的是避免代码重复。

另外,我可以写一些清理函数,但是如果我可以调用析构函数,那又是为了什么呢?

【问题讨论】:

  • 如果调用析构函数,对象不复存在,需要在其位置上构造一个新对象。您可以为此使用带有移动构造函数的placement new。

标签: c++11 destructor move-semantics


【解决方案1】:

原则上,您可以通过这种方式调用析构函数,如果您随后使用placement new 将对象构造回现在为空的空间中。像这样的:

Foo& Foo::operator=(Foo&& from) {
  void* p = this;
  ~Foo();
  return *(new(p) Foo(std::move(from)));  // calls Foo(Foo&&) constructor
}

这种方法有很大的局限性 - 参见例如this answer。例如,如果Foo 具有const-qualified 或引用类型的非静态成员,它将表现出未定义的行为;或者如果此运算符实际应用于从Foo 派生的类的基类子对象。由于这个和其他原因,这并不常见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-19
    • 2020-12-03
    • 2017-10-06
    • 2013-06-11
    • 2017-05-15
    • 2020-09-06
    • 1970-01-01
    • 2013-07-03
    相关资源
    最近更新 更多