The place where random ideas get written down and lost in time.
2024-02-18 - C++ unique_ptr
Category DEVIt’s time to update SDB to use more unique_ptr and/or shared_ptrs.
Some simple examples come to mind:
class SdbModManager {
std::vector<SdbMod*> _mods;
std::map<String, SdbMod*> _modsmap;
std::vector<SdbSensor*> _sensors;
std::vector<SdbServer*> _servers;
std::vector<SdbBlock*> _blocks;
}
All these should be either unique or shared pointers to clarify the ownership.
There are 2 or 3 aspects to clarify:
- How a new object is created.
- How a ptr is “moved” into the vector.
- Users of the vector.
For each collection, I have a simple getter that returns the vector as a reference:
const std::vector<SdbServer*>& servers() const { return _servers; }
and then I use that in a for/auto loop:
for(auto* s: _manager.servers()) { … s->name() … }
The other kind of usage is the vector for Events. One goal here is to change that from a struct holding to holding unique ptrs, with the goal that events get automatically released when pulled out of the vector and used.
So first, I need to write down a few things about how to use unique_ptrs correctly.
https://en.cppreference.com/w/cpp/memory/unique_ptr
#include <memory>
auto p = std::unique_ptr<Class>(new Class())
std::unique_ptr<Class> function() {
return std::unique_ptr<Class>(new Class());
}
C++ ref mentions creating the instances using std::make_unique(), but apparently I don’t have that in the ESP IDF projects (N.D.L.R. it should be in ESP IDF 5.x but I’m using the previous one).