是否有任何方法使类型的大小为零,并且只能隐式构造?
用例是防止通过大括号语法初始化结构的一些公共成员:
class Barrier { ... };
struct Foo {
int user_sets;
int* this_to;
Barrier _bar;
int *must_be_zero_init_by_linker;
};
Foo foo = {1}; // ok
Foo bar = {1, nullptr}; // ok
Foo baz = {1, nullptr, {}}; // must error编辑:另一个约束: Foo对象必须初始化链接器,这样它就不能定义构造函数或私有成员。
发布于 2014-03-10 21:08:56
您可以定义自己的构造函数;这将防止类成为聚合。例如:
struct Foo
{
Foo(int a = 0, int * p = nullptr) constexpr
: user_sets(a), this_to(p), must_be(nullptr)
{}
int user_sets;
int* this_to;
int *must_be;
};
Foo foo = { 1 }; // ok
Foo bar = { 1, nullptr }; // ok
// Foo baz = { 1, nullptr, {} }; // error实际上,我建议将构造函数设置为explicit --这样就不能使用复制初始化,但仍然可以使用列表初始化:
explicit Foo(int a = 0, int * p = nullptr) constexpr /* ... */
Foo foo { 1 }; // ok
Foo bar { 1, nullptr }; // ok
// Foo baz { 1, nullptr, {} }; // error发布于 2014-03-10 22:25:04
是的,一个显式的默认构造函数可以工作:
struct Barrier { explicit constexpr Barrier() {} };这给了你想要的行为:
Foo foo = {1}; // ok
Foo bar = {1, nullptr}; // ok
Foo baz = {1, nullptr, {}}; // error请注意,根据博士1518的最终分辨率,行为可能会发生变化,因此KerrekSB的答案更可靠,也更不微妙。
https://stackoverflow.com/questions/22311274
复制相似问题