Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Down-Upcast for CRTP during construction incorrectly (?) flagged as UB #1773

Open
upsj opened this issue Jul 30, 2024 · 0 comments
Open

Down-Upcast for CRTP during construction incorrectly (?) flagged as UB #1773

upsj opened this issue Jul 30, 2024 · 0 comments

Comments

@upsj
Copy link

upsj commented Jul 30, 2024

Take the following piece of code

#include <iostream>

struct A {
  virtual ~A() = default;
  void foo() { std::cout << "foo"; }
};

template <typename Derived> struct EnableA : A {};

struct B {
  virtual ~B() = default;
  void bar() { std::cout << "bar"; }
};

template <typename Derived> struct EnableB : B {
  EnableB() { static_cast<Derived *>(this)->foo(); }
};

struct C : EnableA<C>, EnableB<C> {};

int main() { C c; }

compiled with UBSAN. We get the following warning:

ubsan-test.cpp:16:15: runtime error: downcast of address 0x7ffc23c64be0 which does not point to an object of type 'C'
0x7ffc23c64be0: note: object is of type 'EnableA<C>'
 00 00 00 00  90 30 40 00 00 00 00 00  70 30 40 00 00 00 00 00  01 00 00 00 00 00 00 00  90 95 c2 51
              ^~~~~~~~~~~~~~~~~~~~~~~
              vptr for 'EnableA<C>'

The static_cast gets flagged as an invalid down-cast, since this has not finished construction. But we are not accessing the Derived object at all, only using it to access the already initialized A class (internally this is static_cast<A*>(static_cast<C*>(this))->foo();)

There has also been a similar discussion on StackOverflow, which sounds like the specification is unclear here, but since we are not calling any virtual functions or using any RTTI, it is not immediately clear why the standard should be interpreted so strictly here.

Related issue: ginkgo-project/ginkgo#1655

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant