是否有一个使用 alloca 的分配器,否则是 C++符合STL标准吗?
我有两个问题:
1)是否可以实现一个使用 alloca 在堆栈上分配内存并且符合 C++ STL 的分配器?
如果有代码,您只需将 URL 指向我即可让我高兴。 :-) 如果没有代码,也许您可以画出分配和释放函数的草图?
2)如果上述问题的答案是“是”,我想了解如何在堆栈上为类成员分配内存。作为一个例子,考虑一个
std::vector<int, AllocaAllocator<int> >
并假设对该向量的成员函数“resize”的调用首先调用分配器的“deallocate”,然后调用“allocate”。
调用 allocate 的范围是成员函数 resize 的范围。这是否意味着在该函数调用结束时分配的内存将从堆栈中删除?
亲切的问候, 比约恩
I have two questions:
1) Is it possible to implement an allocator that uses alloca to allocate memory on the stack and is otherwise C++ STL compliant?
If there is code out there, you can make me happy by simply pointing me to the URL. :-)
If there is no code out there, perhaps you can sketch the functions allocate and deallocate?
2) If the answer to the above question is 'yes', I'd like to understand how it is possible to allocate memory on the stack for class members. As an example, consider an
std::vector<int, AllocaAllocator<int> >
and suppose that a call of the member function 'resize' of this vector calls first 'deallocate' and then 'allocate' of the allocator.
The scope from which allocate is called is that of the member function resize. Doesn't this mean that the allocated memory is removed from the stack at the end of that function call?
Kind regards,
Bjoern
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Bjoern,看来您从根本上误解了堆栈和分配的工作原理。阅读有关他们的信息。
您所要求的是不可能的,因为当您从分配它的函数返回时,alloca 分配的内存将被“释放”(与帕特里克所说不同,内联不能改变其行为)。我写“freed”是因为它实际上并没有被释放,它只是像任何其他堆栈变量一样超出了范围。因此之后使用它会导致未定义的行为。
假设您在
YourAllocator::allocate
中分配了一块内存,该内存是从d.push_back()
调用的:alloca 分配的内存可能会被以下堆栈帧覆盖
push_back
和printf
,因此输出可能不是 42,它可能会崩溃,或者发生任何其他情况。Bjoern, it looks like you fundamentally misunderstand how stack and alloca work. Read about them.
What you are asking is impossible because the memory allocated by alloca is "freed" when you return from the function that allocated it (and unlike Patrick said, inlining cannot change its behavior). I write "freed" because it's not actually freed, it just goes out of scope as any other stack variable. So using it afterwards causes undefined behavior.
Suppose you allocate a chunk of memory in
YourAllocator::allocate
which is called fromd.push_back()
:The memory allocated by alloca may be overwritten by the stack-frames of
push_back
andprintf
, so the output may not be 42, it may crash, or any other thing.不,这种事不可能。首先,STL 期望分配更多内存,然后释放旧内存。你打算如何在堆栈上做到这一点?
唯一与此相当的东西是保守的垃圾收集器。
No, this kind of thing isn't possible. For a start, the STL expects to allocate more memory, then free the old memory. How are you going to do that on the stack?
The only thing even remotely equivalent to this is a conservative garbage collector.