c++ - C ++初始化:无括号与空括号
问题描述
Foo foo;
和有什么区别Foo foo{};
?(以及为什么用户定义的ctor很重要,如下所示)
我写了一些测试代码,发现当没有提供用户定义的ctor时,Foo foo;
会给出一个未初始化的对象,Foo
而Foo foo{};
执行零初始化,但是当提供用户定义的ctor时,两者都会给出未初始化的对象。
#include <iostream>
constexpr std::size_t LEN = 10;
struct Foo
{
Foo() {} // user-defined ctor, though empty
int a[LEN];
};
struct Bar
{
// no user-defined ctor
int a[LEN];
};
template <typename FooBar>
void print(const FooBar &foobar)
{
for (int i = 0; i < LEN; ++i) {
std::cout << foobar.a[i] << ", ";
}
std::cout << std::endl;
}
int main()
{
Foo foo1;
print(foo1);
Foo foo2{};
print(foo2);
Bar bar1;
print(bar1);
Bar bar2{};
print(bar2);
return 0;
}
可能的输出(g++10.3、MSYS2、Win10):
-1369499968, 490, -1788275447, 32759, 1, 0, 2, 0, -1369500000, 490,
1, 0, 0, 0, -1788275056, 32759, 24, 0, 0, 0,
-1788275408, 32759, 8, 0, 0, 0, 268501009, 0, -1369503896, 490,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
解决方案
推荐阅读
- java - 可以在 Java 中使用枚举作为 List 元素吗?
- php - Laravel Guzzle 在 Get() 方法中返回空白响应
- python - 如何在python中迭代非常大的数据框?
- amazon-web-services - AWS 上的 HashiCorp Vault 快速入门:如何从 localhost 通过堡垒连接到 Vault?
- java - 如何使用 Jackson 序列化带有嵌套有效负载的 Flux 样式操作?
- php - 如何在 amcharts 中的图表条内显示值
- java - RESTEasy 与 Guice InstantiationError 在部署(App Engine 本地)
- rate-limiting - 生成资源的球童速率限制
- javascript - 如何在 html 标签中获取内容,包括在 javascript 中使用正则表达式的标签?
- python - 在条形图上包含 0 个值天