开发者

Memory allocation for _M_start and _M_finish in a vector

开发者 https://www.devze.com 2022-12-20 07:59 出处:网络
I\'m defining a vector as: vector< int, MyAlloc< int> > *v = new vector< int, MyAllooc< int> > (4);

I'm defining a vector as:

vector< int, MyAlloc< int> > *v = new vector< int, MyAllooc< int> > (4);

MyAlloc is allocating space for only 4 ints.开发者_开发百科 Memory for _M_start, _M_finish, and _M_end_of_storage is being allocated on the heap before the memory for the 4 ints. But who is allocating this memory for _M_start, _M_finish, and _M_end_of_storage? I want to allocate this memory myself. What do I have to do?


Do not use new for allocating the vector. Generally you should allocate vectors from stack:

vector< int, MyAlloc< int> > v(4);

If you really need to use your own allocator for that too, allocate the memory for the object and then call placement new on it to construct the vector.

It is also possible to overload global operator new/delete, but this is really messy and I would not recommend it.


Allocators allocate the data storage of the container, not the container data members, which are allocated as normal. This must be the case, or you would not be able to create the vector using new or on the stack. This is clearest for a node based container like a list - the list nodes are allocated by the allocator, but the other data members, including the pointers to the first and last nodes (if implemented that way) are allocated normally.


When you create the vector, it allocates room for the vector's member variables (the _M ones) wherever you place the vector. If you use new, it allocates space for these variables on the heap. With local variables, the compiler makes space for them in the current stack frame. If you make the vector a member of a class, the compiler makes space for them in the containing class.

The vector then uses its allocator to allocate room for the data you wish to store in the vector, using whatever mechanism the allocator is defined to use.


new T allocates sizeof(T) memory on the heap. In your case, T is std::vector< int, MyAlloc< int> > and includes members like _M_start.

If you want to allocate that memory yourself, then don't call new.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号