Myclass* obj = new Myclass();
in this statement there are two operation performed.
1. Calling New
2. calling myClass.
As per my understanding when the new is called, memory for the Obj is allocated and then Myclass()[Constructor] is been called.
Is there any difference in the behaviour?
what is the value that obj will hold once the new is called and Myclass() is about to call?
I want to know about the internal behaviour.
This is mainly needed for singleton class.
if (obj == NULL)
obj = new myclass();
when multiple threads tries to access this, then after the new is executed & myclass() is about to execute, will the obj be NULL or it will hold some value?
It will be NULL (maybe). It depends on if your other thread interrupts you in the middle of calling new.
Use some sort of lock or mutex if you need to, or just make sure to initialize the object before you start letting anything access it if you aren't modifying it.
I use something like this to slove this issue.
if (obj == NULL)
myclass *tmp = new myclass();
if (tmp != NULL)
obj = tmp;
but now the question remains same. what temp will hold when new is done and abt to execute myclass, the construction and object mem creation when and where it will happen??
I believe threads get their own local variables and you only need to use mutexes(locks down mutually shared variables) on global variables.
A singleton class will only return 2 things from the constructor. It's either a pointer to a newly created class or a pointer to an already created class.
That's all I know.
Last edited on
Because your instance method is a critical section you will need to use a lock/mutex to ensure only 1 thread can execute it at once.
What you're trying to ask is, can I have it called by multiple threads at once? The answer is no, because what if they both execute new at the same time? Then you have a memory leak.
What if the constructor does something that can only happen once, but is called simultaneously? Then you could end up with undefined behaviour and random crashes.
Even with your checks in place you'll still open to a timing problem.