On 04/03/16 18:34, Richard wrote:
> [Please do not mail me a copy of your followup]
>
> David Brown <
david...@hesbynett.no> spake the secret code
> <nbceo6$311$
1...@dont-email.me> thusly:
>
>> You can use /some/ standard container classes, such as std::array. And
>> I think you could probably use at least some of the other container
>> classes with customer allocators, placement new, memory pools, etc., to
>> use their features without a "dangerous" general purpose heap.
>
> Yes, you could do that. However, it is highly likely that the
> resulting code would be harder to understand than just using a
> fixed-size array. It isn't a question of what is *possible*, it is a
> question of how would you do things in practice under a constrained
> environment where using the heap is out of the question. Avoiding being
> "clever" here is probably the best advice.
On that last point, I agree entirely - being "clever" is rarely a good plan!
Without a heap, classes like vector would be of limited value. However,
I could see the use of a map or queue container of some sort (not
necessarily the standard library types) with either a fixed constant
maximum size, or perhaps with a fixed size given when the structure is
allocated on the stack (like a VLA).
>
>> But are there any other standard library classes or functions that use
>> dynamic memory without it being obvious? I don't know, but I suspect
>> that shared_ptr does [...]
>
> Again -- shared_ptr is for using the heap. Why would you be
> attempting to use shared_ptr when you don't want to use the heap?
The concept of "smart pointers" can be used for a variety of purposes,
not just to track memory. Whenever you have RAII to control a resource,
and you might want to access that resource from several contexts (like
different RTOS threads), you could have a shared pointer type of
management class. But in such cases, you would probably know in advance
exactly how many such managers you would want, and be able to have
statically allocated data (such as reference counters) for them - you
would perhaps want your own specialised sharer class, rather than a
shared_ptr.
There are also other types of dynamic memory that can be allowed in
embedded systems even if a general malloc-style heap is banned. In
systems with Ethernet, it is common to have dynamically allocated
buffers and other resources - but they would come from specific pools in
order to be sure that you have control over allocation/deallocation
times, avoid memory fragmentation, and do not end up with low-priority
processes using all the memory and leaving nothing for high-priority
situations. A standard smart_ptr may be a suitable way of handling such
buffers - but only if the pointer's control block can be allocated in a
controlled manner rather than on the heap.