只能隐式构造的c++ 11类
C++11 class that can only be implicitly constructed?
有没有办法使一个类型的大小为零,只能隐式构造?
用例是为了防止结构体的一些公共成员通过大括号语法初始化:
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对象必须被链接器初始化,所以它不能定义构造函数或私有成员。
你可以定义自己的构造函数;这可以防止您的类成为聚合。例如:
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
是的,一个显式的默认构造函数可以工作:
struct Barrier { explicit constexpr Barrier() {} };
给出你想要的行为:
Foo foo = {1}; // ok
Foo bar = {1, nullptr}; // ok
Foo baz = {1, nullptr, {}}; // error
请注意,行为可能会根据DR 1518的最终分辨率而改变,因此KerrekSB的答案更可靠,更不微妙。
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- "类模板示例<int>;"语句对 C++11 是什么意思?
- 为什么 C++ 11 在 ios 类中添加了运算符 bool
- 如何使用类模拟 C++11 中的 lambda 函数和闭包?
- C++11 中好友模板类的视觉C++错误
- C++ Visual Studio 错误:名称后跟'::'必须是类或命名空间名称 (DirectX 11)
- 如何在 c++11 中静态断言 std::array 类成员进行排序?
- 分段故障 11,从类函数显示动态 C 字符串
- 在 C++11 中轻松初始化模板类的静态成员,没有 clang 警告
- C++11: 如何访问派生类中的基类成员?
- 为什么静态数据成员不能在c++11中的类中初始化
- C++11:我可以显式调用基类析构函数来销毁派生类吗
- 防止复制构造函数实例化 C++11 类"deleting"
- C++11 类中放置的枚举类的重载运算符
- 我能否使 C++11 类/对象通用线程安全?
- C++11 类的分布如何<random>转换底层生成器?
- 带有混合虚基和非虚基的c++ 11类格
- C++11:类初始化赋值顺序的主体
- c++11类成员数组大小constexpr正向声明
- 只能隐式构造的c++ 11类