The pointer-to-member operators
->* are used to obtain an object or a function as though it were a member of an underlying object. For instance, the following are functionally equivalent ways to call the member function
f() on the object
The call of the form
o.f() uses class member access at compile time to look up the address of the function
S::f() on the object
o. The call of the form
(o.*pm)() uses the pointer-to-member operator
.* to call the function at the address specified by
pm. In both cases, the object
o is the implicit
this object within the member function
The C++ Standard, [expr.mptr.oper], paragraph 4 [ISO/IEC 14882-2014], states the following:
Abbreviating pm-expression.*cast-expression as
E1is called the object expression. If the dynamic type of
E1does not contain the member to which
E2refers, the behavior is undefined.
A pointer-to-member expression of the form
E1->*E2 is converted to its equivalent form,
(*(E1)).*E2, so use of pointer-to-member expressions of either form behave equivalently in terms of undefined behavior.
Further, the C++ Standard, [expr.mptr.oper], paragraph 6, in part, states the following:
If the second operand is the null pointer to member value, the behavior is undefined.
Do not use a pointer-to-member expression where the dynamic type of the first operand does not contain the member to which the second operand refers, including the use of a null pointer-to-member value as the second operand.
Noncompliant Code Example
In this noncompliant code example, a pointer-to-member object is obtained from
D::g but is then upcast to be a
B::*. When called on an object whose dynamic type is
D, the pointer-to-member call is well defined. However, the dynamic type of the underlying object is
B, which results in undefined behavior.
In this compliant solution, the upcast is removed, rendering the initial code ill-formed and emphasizing the underlying problem that
B::g() does not exist. This compliant solution assumes that the programmer's intention was to use the correct dynamic type for the underlying object.
Noncompliant Code Example
In this noncompliant code example, a null pointer-to-member value is passed as the second operand to a pointer-to-member expression, resulting in undefined behavior.
In this compliant solution,
gptr is properly initialized to a valid pointer-to-member value instead of to the default value of
|Axivion Bauhaus Suite|
DF2810, DF2811, DF2812, DF2813, DF2814
A cast shall not convert a pointer to a function to any other pointer type, including a pointer to function type
|Parasoft Insure++||Runtime detection|
|Polyspace Bug Finder|
|CERT C++: OOP55-CPP||Checks for pointers to member accessing non-existent class members (rule fully covered).|
This rule is a subset of EXP34-C. Do not dereference null pointers.
Subclause 5.5, "Pointer-to-Member Operators"