[英]use stl map as member of struct
I'm constructing a struct with one of the member being a map.我正在构建一个结构,其中一个成员是地图。
First question is this allowed?第一个问题,这允许吗? The compiler did not complain.
编译器没有抱怨。
struct A {
map<int, float> B;
}
Later I declare an array of such data type.后来我声明了一个这种数据类型的数组。
A *C = (A *)INTERNAL_CALLOC(..., sizeof(A));
Here the function INTERNAL_CALLOC
is a functional wrapper of MALLOC.这里的
INTERNAL_CALLOC
函数是 MALLOC 的功能包装器。
Later on in the code when I try to first time insert an item into the array's first element's map, I got a core dump.稍后在代码中,当我第一次尝试将一个项目插入数组的第一个元素的映射时,我得到了一个核心转储。
C[0].B[0] = 0.001;
Any idea why is this the case?知道为什么会这样吗?
Thanks!谢谢!
Yes, a map in a struct is fine.是的,结构中的地图很好。
Allocating with malloc
is definitely not fine;用
malloc
分配肯定不行; the constructor is not called.不调用构造函数。 So your map will most likely do something terrible when you attempt to use it.
因此,当您尝试使用地图时,您的地图很可能会做一些可怕的事情。
General rule of thumb: don't use malloc
/ calloc
/ realloc
/ free
in C++.一般经验法则:不要在 C++ 中使用
malloc
/ calloc
/ realloc
/ free
。 Avoid dynamic allocation wherever possible, and use new
/ delete
when unavoidable.尽可能避免动态分配,并在不可避免时使用
new
/ delete
。 * *
If you really must allocate with INTERNAL_CALLOC, then use placement new.如果您确实必须使用 INTERNAL_CALLOC 进行分配,则使用新的放置位置。
First, you must define a constructor and a destructor for the type A, or define A as a class:首先,您必须为类型 A 定义一个构造函数和一个析构函数,或者将 A 定义为一个类:
struct A {
A(){}
~A(){}
map<int, float> B;
};
Then you can simply call:然后你可以简单地调用:
//Allocate an A, uninitialized
A *C = (A *)INTERNAL_CALLOC(..., sizeof(A));
//Initialize the newly allocated A
new (C) A();
later when you free the object you must explicitly call the destructor:稍后当您释放对象时,您必须显式调用析构函数:
//A *C;
C->~A();
INTERNAL_free(C);
A *C = (A *)INTERNAL_CALLOC(..., sizeof(A));
Here you are lying to the compiler.在这里,您向编译器撒谎。 You are telling it that the return value from
INTERNAL_CALLOC
points to an A
, but it doesn't, it just points to zeroes.你告诉它
INTERNAL_CALLOC
的返回值指向A
,但它没有,它只是指向零。 Use new
.使用
new
。
使用 malloc 分配内存不会初始化数组元素。
You don't get a valid std::map<whatever...>
by filling memory with zero bytes.通过用零字节填充内存,您不会获得有效的
std::map<whatever...>
。
To a certain extent, it's possible with POD types (approximately, "pure C" data structures).在某种程度上,POD 类型(大约为“纯 C”数据结构)是可能的。
Since you use std::map
as a member, I recommend to use std::vector
instead of plain array to be the container.由于您使用
std::map
作为成员,我建议使用std::vector
而不是普通数组作为容器。
You can do as follow:您可以执行以下操作:
struct A
{
std::map<int, int> B;
};
std::vector<A> vecofmap;
A elem0;
A elem1;
A elem2;
vecofmap.push_back(elem0);
vecofmap.push_back(elem1);
vecofmap.push_back(elem2);
vecofmap[0].B[0] = 100;
std::cout << vecofmap[0].B[0] <<std::endl;
Then no needs to bother with memory allocation.这样就无需费心分配内存了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.