c++11 - 为什么是 int* arr = {};合法的?

标签 c++11 initializer-list

int* arr1 = {}; //ok: arr1 == NULL
int* arr2 = {1,2,3};//error: scalar object requires one element in initializer

我预计 arr1 的初始化会导致相同的错误,但事实并非如此。这是为什么?

编辑:
感谢@krzaq的回答。我确实对你所说的感到困惑。
所以以下语句都是合法的:

int* arr1 = {};
int arr2[] = {1,2,3};
int* arr3 = {arr2};

最佳答案

您对不正确的命名感到困惑。 arr1arr2是指针,不是数组。您可以对指针进行零初始化,并且您可以使用 arr1 所使用的确切语法来完成此操作。 。您不能使用 std::initializer_list<int> 来初始化指针.

如果这仍然让您感到困惑,请尝试推理一些抽象类型:

using some_type = int*;

some_type foo = {}; // ok, value-initialized
some_type bar = {1,2,3}; // not ok, doesn't make sense to initialize 
                         // bar with a list of ints
some_type baz = "a string"; // also not ok, doesn't make sense

关于c++11 - 为什么是 int* arr = {};合法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40668252/

相关文章:

C++:将引用成员初始化为在初始化列表中创建的对象

C++ - 获取派生类型作为模板参数

c++ - 我应该在移动构造函数中 std::move 一个 shared_ptr 吗?

c++ - 清理拥有的 (!) 字符串成员时析构函数偶尔崩溃

c++ - std::atomic 将一对原子 int32 视为一个原子 int64?

c++ - 在 C++ 初始化器列表中初始化动态 C 数组

c++ - 将一个对象的函数传递给另一个类的另一个 std::function

c++ - 集合中的智能指针多态性

c++ - 在 std::Optional 的 noexcept 说明符中引用initializer_list

c++ - 类对象集