rule of zero vs. base class destructors
Asked Answered
C

2

6

I have a base class Base and a derived class D, and I'd like to have move constructor and move assignment operator automatically generated by the compiler for me. Following the Rule of Zero, I leave all memory management to the compiler and only use level-2 classes (no raw pointers, arrays, etc.):

#include <iostream>

class Base{
  public:
    Base(): a_(42) {}
    virtual void show() { std::cout << "Base " << a_ << std::endl; }

  private:
    int a_;
};

class D : Base {
  public:
    D(): b_(666) {}
    void show() { std::cout << "D " << b_ << std::endl; }

  private:
    int b_;
};

int main() {
  Base b;
  b.show();
  D d;
  d.show();
  return 0;
}

This should be it, right?

Enter the C++ core guidelines:

A base class destructor should be either public and virtual, or protected and nonvirtual.

Ah, so I guess I'll have to add a destructor to Base. But that'll do away with the automatically generated move functions!

What's the clean way out here?

Counterblast answered 2/1, 2017 at 10:23 Comment(2)
You can = default the destructor, and declare it public virtual or protected, as you see fit.Marvelofperu
Strongly related: Why does destructor disable generation of implicit move methods?Millikan
A
8

You can = default everything that you would like to be generated by the compiler. See (at the bottom): http://en.cppreference.com/w/cpp/language/rule_of_three

In your case it could look something like:

class Base{
  public:
    Base(): a_(42) {}
    Base(const Base&) = default;
    Base(Base&&) = default;
    Base& operator=(const Base&) = default;
    Base& operator=(Base&&) = default;
    virtual ~Base() = default;

    virtual void show() { std::cout << "Base " << a_ << std::endl; }

  private:
    int a_;
};
Amoeba answered 2/1, 2017 at 10:34 Comment(0)
A
2

You can create once a class like

struct VirtualBase
{
      virtual ~VirtualBase() = default;
      VirtualBase() = default;
      VirtualBase(const VirtualBase&) = default;
      VirtualBase(VirtualBase&&) = default;
      VirtualBase& operator = (const VirtualBase&) = default;
      VirtualBase& operator = (VirtualBase&&) = default;
};

And then follow rule of zero:

class Base : VirtualBase
{
public:
    Base(): a_(42) {}
    virtual void show() { std::cout << "Base " << a_ << std::endl; }

  private:
    int a_;
};
Anxiety answered 2/1, 2017 at 10:38 Comment(3)
Nice suggestion & I was about to write this answer. But wasn't sure, what will be its fate when there is multiple inheritance involved. Isn't it safe to inherit VirtualBase virtually?Millikan
@iammilind: virtual inheritance has a higher cost than simple inheritance, so unless needed, I will stick with normal inheritance.Anxiety
@Millikan it is safe to inherit either virtually or not.Laski

© 2022 - 2024 — McMap. All rights reserved.