Currently, I am testing some with Dynamic libraries and have some trouble with the Data Management/deletion... how can I 'notify' a Pointer that it got invalid?
What I need: Thread safe Way to delete Data from its library and invalidate DataContainers Ptr or a thread safe workaround.
What I tried:
Using Shared/Weak Pointer = Anyone can delete it (the library gets unloaded, but the pointer still exists in another library and deletes it there but doesn't know how.)
Possible solutions:
- Keep a list of DataContainer and set them manually to nullptr on Library Unload.
- Don't use Ptr, use Index to Vector Location and look up everytime the Data is needed.
Simple Example:
class Data
{
public:
Data(std::string Str) : SomeStr(Str) {}
std::string SomeStr;
};
struct DataContainer
{
Data* m_Data = nullptr;
};
int main()
{
// This vector is static inside a Dynamic Library so we need to use UniquePtr,
// to be sure it gets deleted inside its Library when unloaded
// if we could use SharedPtr/WeakPtr it would be too easy... but it could get deleted by anyone
// Protected by Mutex
std::vector<std::unique_ptr<Data>> DataHolder;
DataHolder.push_back(std::make_unique<Data>("Example Str"));
// this could maybe inside another Dynamic Library
DataContainer Container;
Container.m_Data = (*DataHolder.begin()).get();
// As example instead of using a Dynamic Library that would get unloaded here
DataHolder.clear();
// Cannot use m_Data here, it got deleted by the DataHolder but Container don't know that
std::cout << "Str: " << Container.m_Data->SomeStr << std::endl;
return 0;
}