M
Mark Stijnman
I need to use an API in our current project and I have been writing
some wrapper classes for the functionality we need. Unfortunately,
before you can use any API calls, the API must be initialized, and
after your done with the API, it wants you to call a cleanup function.
I am now looking for a safe solution to wrap the API
initialization/cleanup.
I am thinking of something along these lines: every class that needs
the API is privately inherited from a class like this one:
class ApiUser {
public:
ApiUser() {
if (_count==0) API_Init();
_count++;
}
ApiUser(ApiUser& a) {
_count++;
}
~ApiUser() {
_count--;
if (_count==0) API_Cleanup();
}
private:
static unsigned int _count;
};
// In cpp file:
int ApiUser::_count = 0;
So, if class A uses the Api, I would declare
class A: private ApiUser { ... };
Would this be a good solution? The static count variable makes me a
little uncomfortable, especially since I expect that threads will be
used at some point. I could of course use mutexes/locks on the static
variable. Are there any other drawbacks I'm missing?
Are there any other approaches that can be used? I've tried looking for
them, but haven't been able to find it, despite the fact that this must
be a rather commonly occurring thing. How have you solved this? Thanks
for any comments or pointers,
regards Mark
some wrapper classes for the functionality we need. Unfortunately,
before you can use any API calls, the API must be initialized, and
after your done with the API, it wants you to call a cleanup function.
I am now looking for a safe solution to wrap the API
initialization/cleanup.
I am thinking of something along these lines: every class that needs
the API is privately inherited from a class like this one:
class ApiUser {
public:
ApiUser() {
if (_count==0) API_Init();
_count++;
}
ApiUser(ApiUser& a) {
_count++;
}
~ApiUser() {
_count--;
if (_count==0) API_Cleanup();
}
private:
static unsigned int _count;
};
// In cpp file:
int ApiUser::_count = 0;
So, if class A uses the Api, I would declare
class A: private ApiUser { ... };
Would this be a good solution? The static count variable makes me a
little uncomfortable, especially since I expect that threads will be
used at some point. I could of course use mutexes/locks on the static
variable. Are there any other drawbacks I'm missing?
Are there any other approaches that can be used? I've tried looking for
them, but haven't been able to find it, despite the fact that this must
be a rather commonly occurring thing. How have you solved this? Thanks
for any comments or pointers,
regards Mark