C++使用已初始化基类触发VS C4355错误,不关闭告警如何解决?
问题背景
类Z中存在大量不需要修改的业务代码,且C4355告警全局设为错误,明确可以直接禁用该告警但不希望采用该方案。
原有代码如下:
#pragma warning (error: 4355) struct A; struct B; struct MapCompare { A*the; MapCompare(A*a):the(a) {;} bool operator()(int,int) const; }; class Z { A a; B b; std::map<int,int,MapCompare> m; public: Z():m{MapCompare{&a}} {;} ... };
问题描述
需要让MapCompare同时访问a和b两个成员,最初尝试改动最小的写法如下:
#pragma warning (error: 4355) struct A; struct B; struct AB { A a; B b; }; struct MapCompare { AB*the; MapCompare(AB*ab):the(ab) {;} bool operator()(int,int) const; }; class Z : public AB { std::map<int,int,MapCompare> m; public: Z():m{MapCompare{static_cast<AB*>(this)}} {;} ... };
编译报错信息如下:
error C4355: 'this': used in base member initializer list
Visual Studio 2019 (16.9.5) 版本提示在成员初始化列表中使用了this指针,但此时仅访问已完成初始化的基类AB部分(成员初始化顺序按照标准规则,基类初始化先于派生类成员初始化),该操作实际是安全的。
希望找到方法让编译器识别到该操作的安全性,无需直接禁用C4355告警即可通过编译。
现有临时解决方案
目前已实现的临时解决方案如下:
#pragma warning (error: 4355) struct A; struct B; struct AB { A a; B b; }; struct MapCompare { AB*the; MapCompare(AB*ab):the(ab) {;} bool operator()(int,int) const; }; class Z { AB ab; A&a; B&b; std::map<int,int,MapCompare> m; public: Z():m{MapCompare{&ab}},a(ab.a),b(ab.b) {;} ... };
注:当前场景与同类公开问题的场景不同:仅访问已经完成初始化的基类部分,只要成员声明顺序符合要求,操作就是安全的。
内容的提问来源于stack exchange,提问作者Hans Olsson
相关产品推荐
相关产品推荐

