堆分配结构的初始值设定项列表
initializer list for a heap-allocated struct
我有一个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
时会调用
相关文章:
- 访问动态分配列表中的元素
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 如何将 QString 的 QList 分配给列表视图?
- 在成员初始值设定项列表中分配unique_ptr
- 使用列表进行动态结构分配
- C++初始化列表与分配值
- Unique_ptr:在列表中放置时未分配释放的指针
- 通过动态分配插入列表元素
- 我可以在 Boost.Spirit.Qi 中向列表运算符 (%) 提供内存分配提示吗?
- 将空初始化器列表分配给现有向量或地图的效果
- 如何删除列表中的动态分配类对象<T>?
- 声明变量以保存字符串列表时的内存分配
- 存储数据列表并自动分配给结构的最佳方法是什么
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 将节点添加到链接列表中,而无需明确分配内存空间(无需使用新)
- 删除为列表分配的内存
- 我应该重载哪个运算符来捕获列表分配
- 从初始值设定项列表分配给数组
- 正在为结构内部的列表分配空间
- 智能指针和参数列表分配规则