I have a base class that implements many basic functions, and it needs some kind of "storage" (memory block), which should be provided by the class that inherits it (or the user).
class Base
{
public:
Base(void* storage, size_t storageSize) :
storage_{storage},
storageSize_{storageSize}
{
}
~Base()
{
}
private:
void* storage_;
size_t storageSize_;
};
It is important to note that this block of memory used in constructor and destructor.
This works very well when the child class uses static storage:
template<size_t Size>
class StaticObject : public Base
{
public:
StaticObject() :
Base{&storage, Size}
{
}
private:
typename std::aligned_storage<Size>::type staticStorage_;
};
I know that the storage is used before its creation (it is “built” after the base constructor is completed) and after its destruction (“destroyed” before the base destructor starts working), but for trivial std::aligned_storage<...>::type
, it does not matter.
However, this idea does not fully work when I want to use it with dynamically distributed storage:
class DynamicObject : public Base
{
public:
DynamicObject(size_t size) :
DynamicObject{std::unique_ptr<uint8_t>{new uint8_t[size]}, size}
{
}
private:
DynamicObject(std::unique_ptr<uint8_t>&& dynamicStorage, size_t size) :
Base{dynamicStorage.get(), size},
dynamicStorage_{std::move(dynamicStorage)}
{
}
std::unique_ptr<uint8_t> dynamicStorage_;
};
, () , Base
- "" . . , - . , Base
( )...
- - Base
DynamicObject
unique_ptr
Base
- - /, :
, DynamicObject
- , ( ) Base
( ) - , /, "" ...
, - . - , RTOS, (https://github.com/DISTORTEC/distortos) - . Dynamic*.hpp
Static*.hpp
- https://github.com/DISTORTEC/distortos/tree/master/include/distortos
- , , - ? - DynamicObject
? , ?