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

            Bug ID: 105277
           Summary: Pointer to member UB in constant expression is not
                    checked.
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: malorubi at outlook dot com
  Target Milestone: ---

The standard says
[expr.mptr.oper] bullet 4 https://eel.is/c++draft/expr#mptr.oper-4

...
If the dynamic type of E1 does not contain the member to which E2 refers, the
behavior is undefined.
...

This is currently not checked, it is possible to invoke a function pointer
using an expression of invalid dynamic type in a constant expression, without
such call being diagnosed as UB.

Example on compiler explorer: https://godbolt.org/z/s4G8ovs7n

Example verbatim:

=== BEGIN EXAMPLE
struct Base {};

struct Derived1 : Base
{
    int x;

    constexpr int fn() const 
    { return 0; }
};

struct Derived2 : Base
{
    int x;

    constexpr int fn() const
    { return 1; }
};

inline void test()
{
    using common_fn = int (Base::*)() const;
    constexpr Derived1 instance1 {};
    constexpr Derived2 instance2 {};

    constexpr auto ptr1 = (common_fn) &Derived1::fn;
    constexpr auto ptr2 = (common_fn) &Derived2::fn;

    static_assert ((instance1.*ptr1)() == 0);
    static_assert ((instance2.*ptr2)() == 1);

    static_assert ((instance1.*ptr2) () == 1); // ?
    static_assert ((instance2.*ptr1) () == 0); // ?
}
=== END EXAMPLE

Reply via email to