问题描述
我有两个问题:
1) 是否可以实现一个使用 alloca 在堆栈上分配内存并且符合 C++ STL 的分配器?
1) Is it possible to implement an allocator that uses alloca to allocate memory on the stack and is otherwise C++ STL compliant?
如果那里有代码,您只需将我指向 URL 即可让我开心.:-)如果没有代码,也许你可以画出函数分配和解除分配?
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) 如果上述问题的答案是是",我想了解如何在堆栈上为类成员分配内存.例如,考虑一个
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> >
并假设调用此向量的成员函数resize"首先调用分配器的deallocate",然后调用分配器的allocate".
and suppose that a call of the member function 'resize' of this vector calls first 'deallocate' and then 'allocate' of the allocator.
调用 allocate 的范围是成员函数 resize 的范围.这不是意味着在该函数调用结束时从堆栈中删除分配的内存吗?
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?
亲切的问候,比约恩
推荐答案
Bjoern,看来您从根本上误解了 stack 和 alloca 的工作原理.阅读它们.
Bjoern, it looks like you fundamentally misunderstand how stack and alloca work. Read about them.
你问的是不可能的,因为当你从分配它的函数返回时,alloca 分配的内存被释放"了(不像帕特里克所说,内联 不能 改变它的行为).我写freed"是因为它实际上并没有被释放,它只是像任何其他堆栈变量一样超出了范围.所以之后使用它会导致未定义的行为.
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.
假设你在 YourAllocator::allocate
中分配一块内存,它是从 d.push_back()
调用的:
Suppose you allocate a chunk of memory in YourAllocator::allocate
which is called from d.push_back()
:
deque<int, AllocaAllocator> d;
d.push_back(42); // calls alloca
printf("Hello
");
printf("%d
", d[0]);
alloca 分配的内存可能会被 push_back
和 printf
的栈帧覆盖,所以输出可能不是 42,它可能会崩溃,或者任何其他东西.
The memory allocated by alloca may be overwritten by the stack-frames of push_back
and printf
, so the output may not be 42, it may crash, or any other thing.
这篇关于是否有一个使用 alloca 并且符合 C++ STL 的分配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!