public inbox for gcc-bugs@sourceware.org
help / color / mirror / Atom feed
* [Bug c++/96765] New: Base class constructor cast to derived should cause a warning
@ 2020-08-24 11:43 jzwinck at gmail dot com
  2020-08-24 13:10 ` [Bug c++/96765] " redi at gcc dot gnu.org
                   ` (2 more replies)
  0 siblings, 3 replies; 4+ messages in thread
From: jzwinck at gmail dot com @ 2020-08-24 11:43 UTC (permalink / raw)
  To: gcc-bugs

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

^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2022-05-04 16:11 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2020-08-24 11:43 [Bug c++/96765] New: Base class constructor cast to derived should cause a warning jzwinck at gmail dot com
2020-08-24 13:10 ` [Bug c++/96765] " redi at gcc dot gnu.org
2021-12-17  5:56 ` pinskia at gcc dot gnu.org
2022-05-04 16:11 ` jason at gcc dot gnu.org

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).