堆分配结构的初始值设定项列表

initializer list for a heap-allocated struct

本文关键字:列表 分配 结构      更新时间:2023-10-16

我有一个Visual Studio 2008 C++项目,我想在其中堆分配一个结构,并使用初始值设定项列表对其进行初始化。

class Foo {
public:
    explicit Foo( int a );
};
struct Bar {
    Foo foo;
    int b;
};
Bar a = Bar { Foo( 1 ), 2 };      // Works!
Bar* b = new Bar{ Foo( 1 ), 2 };  // Errors!

有办法做到这一点吗?

C++11允许它,或者类似的东西。由于您使用的是VC 2008,然而,这对你没有帮助。我知道的唯一解决方案是创建本地实例初始化,然后传递这个:

Bar forInitialization = { Foo( 1 ), 2 };
Bar* b = new Bar( forInitialization );

尝试

Bar* b = new Bar({ Foo( 1 ), 2 });

免责声明:仅使用GCC -std=c++0x进行测试。

尝试将构造函数添加到结构中,当调用new时会调用