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
  • 3,665
  • 4
  • 21
  • 30
Alex
  • 9,311
  • 11
  • 52
  • 80

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
  • 48,636
  • 4
  • 54
  • 79