1

Well I have non-trivial destructor in my class.

May I do something like:

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

What I am trying to achieve is to avoid code duplication.

Also, I could write some cleanup function, but if I can call destructor then what for?

Sisir
  • 4,584
  • 4
  • 26
  • 37
Alex
  • 9,891
  • 11
  • 53
  • 87
  • If you call the destructor, the object ceases to exist, you need to construct a new one in its place. You can use placement new with a move constructor for that. – n. m. could be an AI Dec 17 '19 at 13:58

1 Answers1

3

You could, in principle, call a destructor this way, if you then use placement new to construct the object back into the now-empty space. Something like this:

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

There are significant limitations to this approach - see e.g. this answer. For example, it would exhibit undefined behavior if Foo has non-static members of const-qualified or reference type; or if this operator is actually applied to a base class subobject of a class derived from Foo. For this and other reasons, this is not commonly done.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85