固定分配std :: vector [英] Fixed allocation std::vector

查看:183
本文介绍了固定分配std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是嵌入式软件开发人员,因此,我不能总是使用所有不错的C ++功能。最困难的事情之一是避免动态内存分配,因为动态内存分配在所有STL容器中普遍存在。

I'm an embedded software developer and as such I can't always use all the nice C++ features. One of the most difficult things is avoiding dynamic memory allocation as it is somewhat universal with all STL containers.

std :: vector 在处理变量数据集时非常有用。不过,问题在于分配(例如 std :: reserve )在初始化或固定时没有完成。

The std::vector is however very useful when working with variable datasets. The problem though is that the allocation(e.g. std::reserve) isn't done at initialization or fixed. This means that memory fragmentation can occur when a copy occurs.

最好让每个向量都有一个分配的内存空间,该空间是向量可以增长到的最大大小。 。这将产生确定性的行为,并有可能在编译时映射微控制器的内存使用情况。在向量达到其最大大小时调用 push_back 会创建一个 std :: bad_alloc

It would be great to have every vector have an allocated memory space which is the max size the vector can grow to. This would create deterministic behaviour and make it possible to map the memory usage of the microcontroller at compilation time. A call to push_back when the vector is at it's max size would create a std::bad_alloc.

我已经读到可以编写 std :: allocator 的替代版本来创建新的分配行为。

是否可以使用 std :: allocator 创建这种行为?或者其他解决方案更合适吗?

I have read that an alternative version of std::allocator can be written to create new allocation behaviour. Would it be possible to create this kind of behaviour with std::allocator or would an alternative solution be a better fit?

我真的很想继续使用STL库并对其进行修改,而不是重新创建自己的向量,因为与实现相比,我更容易出错。

I would really like to keep using the STL libraries and amend to them instead of recreating my own vector as I'm more likely to make mistakes than their implementation.

旁注1:

我不能将 std :: array 用作1:它不是我的编译器提供的; 2:它确实具有静态分配,但是我仍然必须管理我的数据与 std :: array 。这意味着用我要摆脱的分配属性重写 std :: vector

I can't use std::array as 1: it isn't provided by my compiler and 2: it does have a static allocation but I then still have to manage the boundary between my data and buffer inside the std::array. This means rewriting a std::vector with my allocation properties which is what I'm trying to get away from.

推荐答案

您可以实现或重复使用boost的 static_vector ; 具有固定容量的可变大小数组容器。

You can implement or reuse boost's static_vector; A variable-size array container with fixed capacity.

这篇关于固定分配std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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