what standard says about static casting to temporary inheritor?
sometimes (quite rarely) I need to get protected members from existing variables like this:
struct S {
protected:
int i;开发者_如何学C
};
struct T : S {
using S::i;
};
int main() {
S s;
static_cast<T&>(s).i = 0;
}
I'm almost sure this ( static_cast(s) ) is UB, but is someone know what the C++ standard (2003) says about this situation?
This type of operation is actually the basis for implementing the constant reoccurring template pattern, where inside the base-class you actually static_cast
the this
pointer of the base-class to the derived-class template type. Since S
is an unambiguous base class of T
, and you are not accessing any members from the static_cast
that are not already members of S
, I don't see why you would encounter any issues.
Section 5.2.8 on static casting in paragraph 5 states:
An lvalue of type “cv1 B”, where B is a class type, can be cast to type “reference to cv2 D”, where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The result is an lvalue of type “cv2 D.” If the lvalue of type “cv1 B” is actually a sub-object of an object of type D, the lvalue refers to the enclosing object of type D. Otherwise, the result of the cast is undefined.
You seem to be meeting all the requirements that avoid undefined behavior. That is:
- Class
T
is derived fromS
- A pointer conversion from
S
toT
does exist sinceS
is both accessible and an unambiguous base-class ofT
(requirements from 4.10) - You are using the same constant-value-qualification for both types
S
is not a virtual base-class ofT
精彩评论