c++ - Visual Studio 2019 无法正确处理动态结构数组的聚合初始化

标签 c++ visual-c++ new-operator compiler-bug aggregate-initialization

如果使用 VC++ 2017 编译,下面的代码将打印垃圾(或零);如果使用 GCC 或 Clang 编译,则打印“1122”( https://rextester.com/JEV81255 )。这是 VC++ 的错误还是我在这里遗漏了一些东西?

#include <iostream>

struct Item {
    int id;
    int type;
};

int main()
{
    auto items = new Item[2]
    {
        { 1, 1 },
        { 2, 2 }
    };

    std::cout << items[0].id << items[0].type;
    std::cout << items[1].id << items[1].type;
}

同时,如果元素是原始类型(如int),它也可以工作。

最佳答案

我通过编写以下代码使其工作,但数据未存储在堆上。

Item items[] {
    { 1, 1 },
    { 2, 2 }
};

如果您在堆上需要它,请使用下面的解决方案,它似乎适用于 vc++ 编译器。 (请注意,这只是一种解决方法,并不能解决根本问题):

Item* Items[2];
Items[0] = new Item{3,3};
Items[1] = new Item{4,4};

std::cout << (*Items[0]).id << (*Items[0]).type << std::endl;
std::cout << (*Items[1]).id << (*Items[1]).type << std::endl;

或者,您可以使用第一个选项创建数组,然后将其复制到堆上的数组中,如下所示:

Item items[2]{
    {1,1},
    {2,2}
};

Item* hitem = new Item[2];
for(int i = 0; i < 2; i++){
    hitem[i].id = items[i].id + 4;
    hitem[i].type = items[i].type + 4;
}

虽然这很慢,但它的工作原理甚至在 vc++ 编译器上也是如此。 您可以在此处查看完整代码:https://rextester.com/VNJM26393

我不知道为什么它只能这样工作......

关于c++ - Visual Studio 2019 无法正确处理动态结构数组的聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57786717/

相关文章:

c++ - C++中的 friend 声明-公共(public)和私有(private)之间的区别

C++ 事件(焦点)处理

c++ - 文件重定向运算符 ">"不适用于 CreateProcess() API

c++ - 带有地址提示的运算符 new(在另一个对象附近创建一个对象)

c++ - 使用 new 运算符在不知道对象类型的情况下将对象复制到堆

c++ - synology 交叉编译 gcc -std=c++0x

C++ 从数字数组创建 png/位图

c++ - 有什么理由反对在 QueryInterface() 实现中直接调用 AddRef() 吗?

c++ - 如何在 C++17 中读取 UTF-16 文本文件

c++ - 为什么C++在创建数组时不允许 `new`调用构造函数