有什么方法可以使类型的大小为零并且只能隐式构造?
用例是为了防止通过大括号语法初始化结构的某些公共(public)成员:
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 对象必须是链接器初始化的,因此它不能定义构造函数或私有(private)成员。
最佳答案
您可以定义自己的构造函数;这可以防止您的类(class)成为一个聚合体。例如:
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
关于只能隐式构造的C++11类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22311274/