如何在malloc内存中初始化非POD数据 [英] How to initialize non-POD data in malloc memory
问题描述
我有一个结构,其中以std :: list作为其数据成员.该std :: list是std :: pair的集合.
I have a structure which has an std::list as its data member. That std::list is an collection of std::pair.
赞这个(.h文件内)
extern struct_info tt;
typedef struct_s *struct_info;
typedef
struct struct_s {
std::list < std::pair <char*, int> > names;
};
我正在为.cpp文件中的该结构分配内存,如下:
I am allocating memory for this structure in my .cpp file as:
tt = mem_malloc(sizeof(struct_t));
mem_malloc是我自己的内存分配例程.请注意,它已经在.h文件中设为外部.
mem_malloc is my own memory allocating routine. Please note that it is already made extern in .h file.
稍后,当我尝试使用以下代码将任何元素推回列表中时:
Later, when I try to push_back any element into the list with following code:
std::pair <char*, int> myPair = std:make_pair("A", 5);
(tt->names).push_back(myPair);
执行push_back时会崩溃.我不知道这里发生了什么.我是否需要为struct_s构造函数中的列表调用任何构造函数或初始化程序?
It crashes while doing push_back. I do not know what is happening here. Do I need to call any constructor or initializer for the list in struct_s constructor?
你们怎么看?
推荐答案
您不能只分配大小为 sizeof(struct_t)
的内存,并希望能够像使用<这里存在code> struct_t 实例-您需要首先构造它.例如
You can't just allocate memory with size sizeof(struct_t)
and expect to be able to use that memory as if a struct_t
instance existed there - you need to construct it first. E.g.
tt = mem_malloc(sizeof(struct_t));
new (tt) struct_s{}; // <- "placement `new`"
// use `tt`...
tt->~struct_s(); // <- explicit destructor call
// deallocate tt
但是,这是一个糟糕的主意,尤其是如果手动完成.标准库提供了分配器支持-您应该创建一个可以与标准库无缝使用的分配器.
This is however a terrible idea, especially if done manually. The Standard Library provides allocator support - you should create an allocator that can be seamlessly used with the Standard Library instead.
这篇关于如何在malloc内存中初始化非POD数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!