为什么类型变量;不调用默认 CTR
Why does Type variable; does not call the default ctor?
让我们假设下面的类Foo。
struct Foo
{
int i;
bool j;
};
为什么我从以下行得到不同的结果?
int main(void)
{
//I thought the default constructor would be called
Foo foo1;
cout << foo1.i << " : " << foo1.j << endl; // " 4196352 : 0 " --> ctor not called?
//if calling the default constructor explicitly
foo1 = Foo();
cout << foo1.i << " : " << foo1.j << endl; // " 0 : 0" --> ctor called.
}
不应该隐式调用默认 ctor 吗?
根据CPP参考:
如果没有为类类型(结构、类或联合(提供任何类型的用户声明的构造函数,编译器将始终将默认构造函数声明为其类的内联公共成员。
根据C++标准
隐式定义的默认构造函数执行一组 将由用户编写的类执行的类的初始化 该类的默认构造函数,没有 CTOR-nitializer (15.6.2( 和一个空的复合语句。
该类有一个简单的默认收缩器,它不初始化类的成员。所以它们有不确定的值。
这种形式的构造者的呼叫
Foo()
值初始化数据成员。对于基本类型,它意味着零初始化。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 如何使用默认参数等选择模板专业化
- 具有默认模板参数的多态类的模板推导失败
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 初始化具有非默认构造函数的std::数组项的更好方法
- 何时提供默认参数作为模板参数
- 是默认情况下分配给char数组常量的值
- 具有默认值的引用获取函数
- 具有默认模板类型的默认构造函数的类型推导
- 当给定默认值时,为什么此模板参数推导失败
- 修改 VS Code 中的默认C++代码段
- 声明默认的模板化函数
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 如何使用非默认构造函数实例化模板化类
- 如何修复带有 clang 的参数'args'缺少默认参数的问题?
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 格式化浮点值:返回默认值
- 为什么类型变量;不调用默认 CTR