0

I've been reading up on the STL and am keen to use smart pointers, My concern is that they seem to rely heavily on dynamic allocation and therefore the heap.

My experience on embedded is that you use static allocation on the stack as much as possible, which would prevent the use of smart pointers and all their useful functionality.

Am I missing something here or have my methodology completely wrong?

Btw, I'm focused on the STM32 F4 & H7s

  • 1
    Why do you need smart pointer if your objects are automatic, what else functionality you need from smart pointers? – Slava Aug 22 '19 at 21:29
  • 1
    very related/maybe dupe: https://stackoverflow.com/questions/42910711/unique-ptr-heap-and-stack-allocation – NathanOliver Aug 22 '19 at 21:30
  • @NathanOliver looks like dupe to me – Slava Aug 22 '19 at 21:32
  • Smart pointers are a tool. Like any tool, you should know what it does so you can decide when (and when not) to use it. If automatic (i.e. local/member) variables can solve your problem in a simple way, then there's no need to use smart pointers. – alter_igel Aug 22 '19 at 21:33
  • Do you really want to do custom, low-level stack allocation? What kind of lifetimes do your objects need to have? – alter_igel Aug 22 '19 at 21:35
  • They don't just use the heap. They take an allocator type as a template parameter (it just happens that the default is to use the heap via `operator new`). – Cruz Jean Aug 22 '19 at 22:54

1 Answers1

3

std::unique_ptr and std::shared_ptr don't in fact assume that the object whose lifetime they manage is allocated on the heap. You can define a custom deleter for both of these objects to run arbitrary code when the smart pointer goes out of scope.

For std::unique_ptr, the custom deleter is an additional template parameter in the form of a function object, e.g.

auto CustomDeleter = [] (char *p) { delete [] p; };
std::unique_ptr <char, decltype (CustomDeleter)> up (new char [20], CustomDeleter);

For std::shared_ptr, it is an additional parameter to the constructor, e.g.

std::shared_ptr <char> sp (new char [20], CustomDeleter);

Please note that, for std::shared_ptr, a (small) control block is allocated on the heap (you can't use make_shared with a custom deleter).

Of course, my examples show allocation on the heap, but that's just by way of demonstration.

Live demo

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48