I am developing a library with some classes, let's call them C1, C2 and ... Cn
. Each of these classes realize some interfaces, i.e. I1, I2, ... Im.
(n > m). The relationship between objects in the library is complex and I have to provide some API for my library users to access these objects using smart pointers.
After some discussions, I found that returning shared pointers to the library users is not a good idea, because in that case I cannot make sure that the object can be unloaded precisely in my library. Returning weak pointers have the same issue, because if the user of the API lock the weak pointer and keep the resulted shared pointer somewhere, I will face the same problem again.
The final idea I have, is to expose some kind of wrappers for the weak pointers. A wrapper class can be something like this:
class Wrapper_C1 : public I1
{
std::weak_ptr<C1> mC1;
public:
Wrapper_C1() = delete;
Wrapper_C1(const std::weak_ptr<C1> & c1) : mC1(c1)
{
}
int method1_C1(int x)
{
if (auto sp = mC1.lock())
{
sp->method1_C1();
}
else
{
throw std::Exception("object C1 is not loaded in the lib.");
}
}
void method2_C1(double y)
{
if (auto sp = mC1.lock())
{
sp->method2_C1(y);
}
else
{
throw std::Exception("object C1 is not loaded in the lib.");
}
}
// The same for other methods
}
As you see, all of this wrapper classes, share the same implementation. What is the best way to factor the code of ALL of these wrapper classes? Is there anyway to avoid repeating the similar codes?
Aucun commentaire:
Enregistrer un commentaire