有一个allocator使用alloca,否则是C ++ STL兼容? [英] Is there an allocator that uses alloca and is otherwise C++ STL compliant?

查看:362
本文介绍了有一个allocator使用alloca,否则是C ++ STL兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题:



1)是否可以实现一个使用alloca在堆栈上分配内存的分配器,否则是C ++ STL兼容? p>

如果有代码,你可以让我快乐,只需指向我的URL。 :-)
如果没有代码,也许你可以草拟函数allocate和deallocate?



2)如果上面的问题的答案是'yes',我想了解如何在类成员的堆栈上分配内存。作为示例,考虑

  std :: vector< int,AllocaAllocator< int> > 

并且假设调用该向量的成员函数'resize'首先调用'deallocate'然后分配器的分配。



调用分配的范围是成员函数resize的范围。这不是意味着分配的内存在函数调用结束时从堆栈中删除?



请注意,
Bjoern

解决方案

Bjoern,它看起来像你从根本上误解stack和alloca如何工作。



你所要求的是不可能的,因为alloca分配的内存在从分配函数返回时是释放的(而不像Patrick说的,内联不能更改其行为)。我写释放,因为它实际上没有释放,它只是超出范围作为任何其他堆栈变量。因此,以后使用它会导致未定义的行为。



假设你在 YourAllocator :: allocate 中分配一块内存,从 d.push_back()调用:

  deque< int,AllocaAllocator> ; d; 
d.push_back(42); // calls alloca
printf(Hello\\\
);
printf(%d\\\
,d [0]);

alloca分配的内存可能被 push_back printf ,因此输出可能不是42,它可能会崩溃,或任何其他的东西。


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

解决方案

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 from d.push_back():

deque<int, AllocaAllocator> d;
d.push_back(42); // calls alloca
printf("Hello\n");
printf("%d\n", d[0]);

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.

这篇关于有一个allocator使用alloca,否则是C ++ STL兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆