【发布时间】:2016-10-02 06:23:42
【问题描述】:
是否可以在我自己定义的默认 ctor 中调用聚合初始化?
GCC 使用以下代码抱怨“错误:构造函数委托给自身”:
struct X {
int x, y, z, p, q, r;
X(): x{}, y{}, z{}, p{}, q{}, r{} { } // cumbersome
//X(): X{} { } // the idea is nice but doesn't compile
};
我现在在 ctor 正文中使用memset(this, 0, sizeof(*this))。
【问题讨论】:
-
如果
X本身不必是聚合,您可以将x, y, z...移动到基类,并在成员初始化列表中聚合初始化该基类 -
@PiotrSkotnicki 很有趣的想法,但如果我在生产代码中这样做,我的同事们会皱眉头。
-
memset(this, 0, sizeof(*this)) 正在伤害我内心的平静...
标签: c++ c++11 constructor aggregate-initialization delegating-constructor