开发者

what standard says about static casting to temporary inheritor?

开发者 https://www.devze.com 2023-04-06 05:30 出处:网络
sometimes (quite rarely) I need to get protected members from existing variables like this: struct S { protected:

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:

  1. Class T is derived from S
  2. A pointer conversion from S to T does exist since S is both accessible and an unambiguous base-class of T (requirements from 4.10)
  3. You are using the same constant-value-qualification for both types
  4. S is not a virtual base-class of T
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号