https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96765

            Bug ID: 96765
           Summary: Base class constructor cast to derived should cause a
                    warning
           Product: gcc
           Version: 10.2.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jzwinck at gmail dot com
  Target Milestone: ---

If I cast "this" in a base class constructor to a derived class type, there is
no warning even with -Wall -Wextra.  Such a cast is undefined behavior, and
seems like it should be diagnosed at compile time.

For example:

    struct Base
    {
      Base();
      int num;
    };

    struct Derived : Base
    {
      int calc() const { return 42; }
    };

    Base::Base()
      // UB: Derived not yet constructed
      : num(static_cast<Derived*>(this)->calc())
    {
    }

    int main()
    {
      Derived d;
      return d.num;
    }

It compiles cleanly with "-Wall -Wextra -Werror" in GCC 8 and 10, with and
without optimization.  I think it should produce a diagnostic such as "invalid
static_cast from type ‘Base*’ to type ‘Derived*’ before the latter is
constructed".

UBSan reports the undefined behavior if Base has a virtual method (e.g. if you
add "virtual ~Base() = default;"), but not with the code as written, making it
even more advantageous to diagnose at compile time.

Live demo: https://godbolt.org/z/x3fa4Y

Reply via email to