How to initial static member in C++ using function - c++

I am using C++.
in .h:
static CRITICAL_SECTION g_CS;
in .cpp:
CRITICAL_SECTION CQCommon::g_CS;
but I want to use
QGUID temp;
EnterCriticalSection(&g_CS);
temp = g_GUID++;
LeaveCriticalSection(&g_CS);
return temp;
in one static function.
How can I invoke InitializeCriticalSection(PCRITICAL_SECTION pcs);?
Can I using the following one:
QGUID func(XXX)
{
static {
InitializeCriticalSection(&g_CS);
}
QGUID temp;
EnterCriticalSection(&g_CS);
temp = g_GUID++;
LeaveCriticalSection(&g_CS);
return temp;
}
And how can I invoke DeleteCriticalSection(&g_CS) after app leave?
Using MFC, it seems CCriticalSection is a solution.

If you want a different approach you can create an object to manage it:
class CriticalSectionManager
{
public:
CriticalSectionManager()
{
InitializeCriticalSection(&g_CS);
}
~CriticalSectionManager()
{
DeleteCriticalSection(&g_CS);
}
};
void Func(void)
{
static CriticalSectionManager man;
//Do stuff
}
This will now be managed automatically by C++. The critical section will be initialized when the function is first entered, and deleted when the program exits.
Furthermore you can extend this by having the actual PCRITICAL_SECTION variable inside the class, etc.. etc..

In the entry point to your code - the main function, call the init:
int main(...)
{
InitializeCriticalSection(&g_CS);
// do some stuff
DeleteCriticalSection(&g_CS);
// exit
return 0;
}

Well, today the best practice is to use "scoped lock" pattern instead of EnterXXX and LeaveXX -like functions. Take a look at what boos has to offer.
Regardless, an RAII approach can help you here:
class MyCriticalSection
{
private:
CRITICAL_SECTION m_CS;
public:
MyCriticalSection()
{
::InitializeCriticalSection(&m_CS);
}
~MyCriticalSection()
{
::DeleteCriticalSection(&m_CS);
}
void Lock()
{
::EnterCriticalSection(&m_CS);
}
void UnLock()
{
::LeaveCriticalSetion(&m_CS);
}
}

Related

Check if class is instantiated in method

I have a class that has a few static functions that can be called even if there is no instance of that class. There is also a method init() that I use to set some variables. This method is not static thus it needs an instance. Now if this was done I want the static methods to behave differently. Sort of like:
static foo(){
if(noInstance()){
doA();
}else(){
doB();
}
}
Is this even possible? Or a bad idea and should just make the user call different methods if there is an instance?
Thanks
EDIT
It sounds weird but this is my use case:
class A{
public:
static inline bool hasInstance = false;
int data;
static int getData(){
if(hasInstance){
return data; // Can't do this from a static function
}else{
return 0;
}
}
};
I know that I cant access the data from a static function beacuse there is no this pointer. I'm coding a library and I want the user to be able to use the static method if he dosen't want an instance but if there is an instance it should make use of the data of its instance.
If had an idea but I don't know wether that's good style:
static int getData(A *ref){
if(ref != nullptr){
return data;
}else{
return 0;
}
}
I'd glad to hear from someone with more experience wether I should do that.
I think you can use a static variable, let it be named count. You initialize count with 0, and every time you create an instance of that class, you increment count. If count is 0, that means you did not created any instance, therefore you can't use some methods.
I'm coding a library and I want the user to be able to use the static method if he dosen't want an instance but if there is an instance it should make use of the data of its instance.
In general, free functions are recommended rather than member functions (gotw). It is actually rare to have good reasons to make a static function a member function. It would need to be a member if it would need access to privates of the class, but that doesnt seem to be the case here and then it still could be a friend function.
Let's look at your approach:
static int getData(A *ref){
if(ref != nullptr){
return data;
}else{
return 0;
}
}
You probably meant to write ref->data;, also I guess you are not merely returning the value of the member. That would be of little use, because If I have an instance I can get my hands on x.data without needing to call getData. And I suppose 0 is just a placeholder for someother value that you have there in the real code.
I am going a bit subjective now...
If I was a user of your library, I would want to know if getData returns data from one of the objects I did create or something else. Having one and the same function that does both would confuse me. I don't like pointers and I am scared of nullpointers, so if you force me to write
getData(nullptr);
this would not make me happy. I would like to have two different functions:
int getData() { return 0; }
int getData(const A& x) { return x.data; }
If I have no instance, I can call the first, if I have one I can call the second.
Not sure what is your final goal, but I would recommend reconsidering your design, because this static/hasInstance behavior smells.
Anyway, here is what you need:
using namespace std;
#include <iostream>
class MyClass
{
private:
static bool hasInstance;
public:
MyClass()
{
hasInstance = true;
}
static void foo()
{
if (hasInstance) {
std::cout << "I have an instance\n";
}
else {
std::cout << "No instance\n";
}
}
};
bool MyClass::hasInstance = false;
int main () {
MyClass::foo();
MyClass a;
a.foo();
MyClass::foo();
return 0;
}
EDIT:
Don't use it in real code. If you just curious, you can do almost everything in C++, so you could pass the object sometimes, it's dirty and ugly, but just for the demo:
using namespace std;
#include <iostream>
class MyClass
{
private:
int someVariable;
public:
MyClass()
{
someVariable = 42;
}
static void foo(MyClass *obj = nullptr)
{
if (obj) {
std::cout << obj->someVariable << std::endl;
}
else {
std::cout << "No instance\n";
}
}
};
int main () {
MyClass::foo();
MyClass a;
a.foo(&a);
MyClass::foo(&a);
return 0;
}

Assignment within RAII scope

Problem
How do you initialize an object inside a RAII scope, and use it outside of that scope?
Background
I have a global lock which can be called with lock() and unlock().
I have a type, LockedObject, which can only be initialized when the global lock is locked.
I have a function, use_locked(LockedObject &locked_object), which needs to be called with the global lock unlocked.
The usage scenario is
lock();
LockedObject locked_object;
unlock();
use_locked(locked_object);
RAII
For various reasons, I moved to a RAII encapsulation of the global lock. I would like to use this everywhere, primarily as creating LockedObject can fail with exceptions.
The problem is that
{
GlobalLock global_lock;
LockedObject locked_object;
}
use_locked(locked_object);
fails, as locked_object is created in the inner scope.
Examples
Set-up (mostly not important):
#include <assert.h>
#include <iostream>
bool locked = false;
void lock() {
assert(!locked);
locked = true;
}
void unlock() {
assert(locked);
locked = false;
}
class LockedObject {
public:
LockedObject(int i) {
assert(locked);
std::cout << "Initialized: " << i << std::endl;
}
};
void use_locked(LockedObject locked_object) {
assert(!locked);
}
class GlobalLock {
public:
GlobalLock() {
lock();
}
~GlobalLock() {
unlock();
}
};
Original, non RAII method:
void manual() {
lock();
LockedObject locked_object(123);
unlock();
use_locked(locked_object);
}
Broken RAII methods:
/*
void raii_broken_scoping() {
{
GlobalLock global_lock;
// Initialized in the wrong scope
LockedObject locked_object(123);
}
use_locked(locked_object);
}
*/
/*
void raii_broken_initialization() {
// No empty initialization
// Alternatively, empty initialization requires lock
LockedObject locked_object;
{
GlobalLock global_lock;
locked_object = LockedObject(123);
}
use_locked(locked_object);
}
*/
And a main function:
int main(int, char **) {
manual();
// raii_broken_scoping();
// raii_broken_initialization;
}
For what it's worth, in Python I would do:
with GlobalLock():
locked_object = LockedObject(123)
I want the equivalent of that. I mention my current solution in an answer, but it feels clumsy.
The specific (but simplified) code to be executed follows. With my current lambda-based call:
boost::python::api::object wrapped_object = [&c_object] () {
GIL lock_gil;
return boost::python::api::object(boost::ref(c_object));
} ();
auto thread = std::thread(use_wrapped_object, c_object);
with
class GIL {
public:
GIL();
~GIL();
private:
GIL(const GIL&);
PyGILState_STATE gilstate;
};
GIL::GIL() {
gilstate = PyGILState_Ensure();
}
GIL::~GIL() {
PyGILState_Release(gilstate);
}
boost::python::api::objects must be created with the GIL and the thread must be created without the GIL. The PyGILState struct and function calls are all given to me by CPython's C API, so I can only wrap them.
Allocate your object on the heap and use some pointers:
std::unique_ptr<LockedObject> locked_object;
{
GlobalLock global_lock;
locked_object.reset(new LockedObject());
}
use_locked(locked_object);
Here is a complete list of options from my perspective. optional would be what I would do:
The proposed post-C++1y optional would solve your problem, as it lets you construct data after declaration, as would heap based unique_ptr solutions. Roll your own, or steal ot from boost
A 'run at end of scope' RAII function storer (with 'commit') can also make this code less crazy, as can letting your locks be manually disengaged within their scope.
template<class F>
struct run_at_end_of_scope {
F f;
bool Skip;
void commit(){ if (!Skip) f(); Skip = true; }
void skip() { Skip = true; }
~run_at_end_of_scope(){commit();}
};
template<class F>
run_at_end_of_scope<F> at_end(F&&f){ return {std::forward<F>(f), false}; }
then:
auto later = at_end([&]{ /*code*/ });
and you can later.commit(); or later.skip(); to run the code earlier or skip running it.
Making your RAII locking classes have move constructors would let you do construction in another scope, and return via move (possibly elided).
LockedObject make_LockedObject(){
GlobalLock lock;
return {};
}
My current solution is to use an anonymous function:
void raii_return() {
LockedObject locked_object = [&] () {
GlobalLock global_lock;
return LockedObject(123);
} ();
use_locked(locked_object);
}
The advantage of this approach is that it avoids pointers and thanks to copy elision it should be quite fast.
One downside is that LockedObjects don't necessarily support copying (use_locked would in that case take a reference).

Mutex/Lock with scope/codeblock

I remember seeing it in some conference, but can't find any information on this.
I want something like:
lock(_somelock)
{
if (_someBool)
return;
DoStuff();
} // Implicit unlock
Instead of:
lock(_somelock);
if (_someBool)
{
unlock(_somelock);
return;
}
DoStuff();
unlock(_somelock);
As you can see the code gets very bloated with multiple early returns.
Obviously one could make another function to handle locking/unlocking, but it's a lot nicer no?
Possible with C++11 standard library?
Yes, you can use a std::lock_guard to wrap a mutex.
{
std::lock_guard<std::mutex> lock(your_mutex);
if (_someBool)
return;
DoStuff();
}
The standard idiom is to use a guard object whose lifetime encompasses the locked state of the mutex:
std::mutex m;
int shared_data;
// somewhere else
void foo()
{
int x = compute_something();
{
std::lock_guard<std::mutex> guard(m);
shared_data += x;
}
some_extra_work();
}
You can simply create an autolock of your own.
Class AutoLock
{
pthread_mutex_t *mpLockObj;
AutoLock(pthread_mutex_t& mpLockObj)
{
mpLockObj = &mpLockObj;
pthread_mutex_lock(mpLockObj);
}
~AutoLock()
{
pthread_mutex_unlock(mpLockObj);
}
};
use like:
#define LOCK(obj) AutoLock LocObj(obj);
int main()
{
pthread_mutex_t lock;
LOCK(lock);
return 0;
}

Is there a generic way to preserve state variables on the stack in C++?

In the program I'm currently working on, a number of the objects include state variables which persist with the object. e.g. an object representing a point in 3d model might include a variable to control whether that point has been selected for editing. Quite regularly, one or more of these state variables will be temporarily modified by a piece of code, e.g.
void MyFunc();
{
mytype temp = statevar;
statevar = newvalue;
DoSomething();
statevar = temp;
}
This has got problems, as if DoSomething() throws an exception, statevar is not restored correctly. My planned workaround is to create a new template class that restores the value in its dtor. Something like
template<class TYPE> class PushState
{
PushState(TYPE Var) { Temp = Var; }
Pop() { Var = Temp; }
~PushState() { Pop(); }
TYPE Temp;
}
void MyFunc();
{
PushState<mytype> Push(statevar);
DoSomething();
}
Is there a better way to do this, or a well accepted method of pushing variables to the stack?
Another option is to use an ad hoc RAII class.
For example:
void MyFunc();
{
class Finally {
mytype temp;
public:
Finally( ) { temp = statevar; }
~Finally() {
statevar = temp;
}
} finally;
statevar = newvalue;
DoSomething();
}
Whether the function returns normally or throws an exception, the destructor is called automatically when finally goes out of scope.
You can use Boost.ScopeExit. This will instantiate an object whose destructor will execute the scope exit code. It just hides all the boilerplate code for you.
#include <boost/scope_exit.hpp>
void MyFunc() {
mytype temp = statevar;
statevar = newvalue;
BOOST_SCOPE_EXIT(&statevar) {
statevar = temp;
} BOOST_SCOPE_EXIT_END
DoSomething();
}

c++ #define a macro with brackets?

Instead of doing the following everytime
start();
// some code here
stop();
I would like to define some sort of macro which makes it possible to write like:
startstop()
{
//code here
}
Is it possible in C++?
You can do something very close using a small C++ helper class.
class StartStopper {
public:
StartStopper() { start(); }
~StartStopper() { stop(); }
};
Then in your code:
{
StartStopper ss;
// code here
}
When execution enters the block and constructs the ss variable, the start() function will be called. When execution leaves the block, the StartStopper destructor will be automatically called and will then call stop().
The idiomatic way of doing this in C++ is called Resource Acquisition Is Initialization, or shortly RAII. In addition to providing what you want, it also has the added benefit of being exception safe: the stop function will be called even if your code throws an exception.
Define a guard struct:
struct startstop_guard
{
startstop_guard()
{
start();
}
~startstop_guard()
{
stop();
}
};
and then rewrite your code this way:
{
startstop_guard g;
// your code
}
The guard's destructor (and thus the stop function) will be called automatically at the end of the enclosing block.
Other answers have addressed the RAII side of the question well, so I'm going to address the syntax side of it.
#define startstop for(Starter s; s.loop; s.loop = false)
struct Starter {
bool loop;
Starter() { start(); loop = true; }
~Starter() { stop(); }
};
Used like:
startstop {
// some code
}
Should be self-explanatory enough.
#define startstop(x, y, ...) for( /* use macro args */ )
Generic solution with RAII and boost::function ( std::function ).
class starter
{
typedef boost::function< void () > action;
action end_;
public:
starter(action start, action end):
end_(end)
{
log("starter start");
start();
}
~starter()
{
log("starter end");
end_() ;
}
};
int main()
{
{
starter s(start, stop);
middle();
}
return 0;
}
or to test and check the idea
void print(const std::string& message)
{
std::cout << message << std::endl;
}
int main()
{
starter s(boost::bind(print, "globalstart"),
boost::bind(print, "globalend"));
{
starter s(boost::bind(print, "start"),
boost::bind(print, "end"));
std::cout << "middle" << std::endl;
}
return 0;
}
What are you trying to do? I'd recommend checking out RAII as a much more C++ oriented way of doing things than macro hacking, with all its unforeseen consequences.
Don't use macros. You can use inline functions instead as it provides type checking and other features. You can take a look here: inline functions
credit to dirkgently for the idea.. I thought I'd fill the rest in
#define startstop() for(start();isStarted();stop())
In c#, you could use the IDisposable pattern, and implement your Stop() functionality in the Dispose() method, but that would would work if you were using a .net variant of c++.