In a singleton class (in my case C++), if one method is called more than once, will the locals be on the stack? - singleton

i have singleton class , when calling one of the singleton methods more then once in the same time , and this method has local variables . does each method call of the singleton gets its own private stack , do i need to worry about sharing/mixing local variable data between calls ?

Using local variables in a class method (not important whether it is a singleton) is no different from using local variables in a regular function. The local variables will not get mixed up.

No, you do not need to worry about that. To correct your terminology: "does each method call of the singleton gets its own private stack" -- not its own stack but each method call gets its own stack frame so you are alright.
A singleton method is just the same as an ordinary function (in C++). Think of local variables in the same way.
Note that this does not apply to static local variables, which are specifically shared between method calls.

Each method will gets its own private stack. The only possibility to take care about sharing are static variables inside the class.... but as ur class is singleton that applies to the instance variables of ur class too. Local variables of the method would always be freash in the stack no need to take care about them.

I'm not sure if you're talking about recursion or multiple thread calls, so I'll assume you mean recursion.
Each time you call the method any local variables that are not declared static are allocated on the stack. The way this works is that each call has it's own stack "frame" When the call is finished, the stack frame is released (and all local variables are destroyed).
So when function foo() is called it's local variables are in a frame on the stack, let's call it frame A. If foo calls itself, another frame is added, let's call it B. During the life of this second call, both frames A and B exist, but A is essentially dormant (usually, the data in A can be modified indirectly, e.g. via pointers). When the second call exits the B frame is released and the A frame becomes active again. Finally, when the top call is finished, the A frame goes away.
Since there is a limited amount of stack space, you have to be careful not to create more frames than the stack can hold. If you do, the stack is said to "overflow".

Related

Objective C++ block semantics

Consider the following C++ method:
class Worker{
....
private Node *node
};
void Worker::Work()
{
NSBlockOperation *op=[NSBlockOperation blockOperationWithBlock: ^{
Tool hammer(node);
hammer.Use();
}];
....
}
What, exactly, does the block capture when it captures "node"? The language specification for blocks, http://clang.llvm.org/docs/BlockLanguageSpec.html, is clear for other cases:
Variables used within the scope of the compound statement are bound to the Block in the normal manner with the exception of those in automatic (stack) storage. Thus one may access functions and global variables as one would expect, as well as static local variables. [testme]
Local automatic (stack) variables referenced within the compound statement of a Block are imported and captured by the Block as const copies.
But here, do we capture the current value of this? A copy of this using Worker’s copy constructor? Or a reference to the place where node is stored?
In particular, suppose we say
{
Worker fred(someNode);
fred.Work();
}
The object fred may not exist any more when the block gets run. What is the value of node? (Assume that the underlying Node objects live forever, but Workers come and go.)
If instead we wrote
void Worker::Work()
{
Node *myNode=node;
NSBlockOperation *op=[NSBlockOperation blockOperationWithBlock: ^{
Tool hammer(myNode);
hammer.Use();
}];
....
}
is the outcome different?
According to this page:
In general you can use C++ objects within a block. Within a member
function, references to member variables and functions are via an
implicitly imported this pointer and thus appear mutable. There are
two considerations that apply if a block is copied:
If you have a __block storage class for what would have been a
stack-based C++ object, then the usual copy constructor is used.
If
you use any other C++ stack-based object from within a block, it must
have a const copy constructor. The C++ object is then copied using
that constructor.
Empirically, I observe that it const copies the this pointer into the block. If the C++ instance pointed to by this is no longer at that address when the block executes (for instance, if the Worker instance on which Worker::Work() is called was stack-allocated on a higher frame), then you will get an EXC_BAD_ACCESS or worse (i.e. pointer aliasing). So it appears that:
It is capturing this, not copying instance variables by value.
Nothing is being done to keep the object pointed to by this alive.
Alternately, if I reference a locally stack-allocated (i.e. declared in this stack frame/scope) C++ object, I observe that its copy constructor gets called when it is initially captured by the block, and then again whenever the block is copied (for instance, by the operation queue when you enqueue the operation.)
To address your questions specifically:
But here, do we capture the current value of this? A copy of this using Worker’s copy constructor? Or a reference to the place where node is stored?
We capture this. Consider it a const-copy of an intptr_t if that helps.
The object fred may not exist any more when the block gets run. What is the value of node? (Assume that the underlying Node objects live forever, but Workers come and go.)
In this case, this has been captured by-value and node is effectively a pointer with the value this + <offset of node in Worker> but since the Worker instance is gone, it's effectively a garbage pointer.
I would infer no magic or other behavior other than exactly what's described in those docs.
In C++, when you write an instance variable node, without explicitly writing something->node, it is implicitly this->node. (Similar to how in Objective-C, if you write an instance variable node, without explicitly writing something->node, it is implicitly self->node.)
So the variable which is being used is this, and it is this that is captured. (Technically this is described in the standard as a separate expression type of its own, not a variable; but for all intents and purposes it acts as an implicit local variable of type Worker *const.) As with all non-__block variables, capturing it makes a const copy of this.
Blocks have memory management semantics when they capture a variable of Objective-C object pointer type. However, this does not have Objective-C object pointer type, so nothing is done with it in terms of memory management. (There is nothing that can be done in terms of C++ memory management anyway.) So yes, the C++ object pointed to by this could be invalid by the time the block runs.

Using Pointers safely in Objective-C

Lets say I have an object with an integer instance variables and 1 member function. The function runs on a separate thread, and consistently updates the value of the instance variable. I have a second function (part of a different class) that also runs on a separate thread, and needs real time access to the integer instance variable in the first object. Therefore, I pass in a pointer to the instance variable to the second function and the second function just dereferences the pointer. This way the second function always has access to the updated value of the instance variable.
However, I do not want the second function to be able to change the value of the instance variable. I want it to have read-only access, but since I am passing in a pointer to the instance variable, will it be able to change the value of the instance variable? If so, how do I restrict pointer dereferencing to read only? If this isn't possible, what would be the safest solution to this problem?
Mac OS X Snowleopard, Xcode 3.2.6. Objective-C with Cocoa.
EDIT: Sorry I forgot to mention that I can't make the instance variable constant, because I need the class it belongs to to be able to modify it. If I make it constant, it would completely restricting writing to the variable.
You can use the type system here. Instead of having something like int* you can have const int *, which means it's a pointer to a constant int. It's possible to get around this by casting back to (int *) inside the function, but this is a violation of the type system (hence the explicit cast) and well-behaved functions won't do that.
Note, you may also need to throw in volatile if your function needs to make sure it has the up-to-date value. Otherwise the compiler may decide it's ok to cache the results of the dereference somewhere.
The right way to do this is make the instance variable a property, and to give the second function a pointer to the object instead of a pointer to the instance variable. The code can then call the object's accessor for the property. It's not clear how your code is structured, but it's also possible to make the property read-only for method outside the class definition, and read-write for methods that are part of the class.
Finally, since you're accessing the property from more than one thread, you'll need to provide some sort of synchronization to avoid having both threads try to access the property at the same time. The simplest way to do that is to omit 'nonatomic' (which is how most people reflexively declare their properties) from the property declaration, which will cause the property accessors to be atomic. The second simplest way is to use the #synchronized directive.

What happens when a method is called? Where are the arguments pushed?

When you call an method, for example, [objectA message:arg1 argument:arg2], what happens to the arguments?
For example, when you call a method, the address of that method is pushed to the call stack. But what happens to the arguments? Aren't they pushed to some stack too? Otherwise, how does the code of the method know where to find its arguments?
The reason I ask is because when you get a stack trace, you get the address of the functions or methods that have been called in order. When a method or function returns, the one that called it still has a reference to its own arguments. So there must me a reference to arg1 and arg2 somewhere. Therefore, from a stack trace and stack symbols on an iOS device, you must be able to get the method or function that called any other method or function, and also get its arguments.
How do you get these arguments?
On this other question: objective C log method call, they show a method to get the NSMethodSignature of a method and using that you can get the number and type of argument.
With that, an knowing where the arguments are located, you could get every function or method that has been called and the arguments that were used to call them.
Any help would be appreciated.
UPDATES
2011-08-03
In reply to "fakeAccount22" comments, I would like to do this at run-time from within the app.
My question basically boils down to: at run-time and within the app, how do you access the call stack or the stack pointer in Objective-C for an iOS device? Is it different for Mac OSX?
The key moment here is that when you invoke
[objectA message:arg1 argument:arg2]
you don't call method but you're sending message. Why? Cause in the end this line is translated by compiler into this:
objc_msgSend(objectA, "message:argument:", arg1, arg2)
That's all the magic. Everything else works as in C. Here is quite good explanation.
That's why all Objective C methods could be translated to their C-analogous (well, they are actually do translated). E.g. your example looks like this:
return_type method(id self, SEL _cmd, arg1_type arg1, arg2_type arg2) {
//implementation
}
Beside what Max wrote, the names and arguments of a method are known because the compiler generates a huge load of debug information, generated from the source code, and the debugger can use that to find names of methods and the names and values of their arguments, etc. This debug info is usually not easily available when you run your code without the debugger, although it ought to be accessible somehow, if you know the format how it is stored. But note that it can change with every new compilation.
Before a function call, the arguments get pushed on the call stack by the calling code, and when the call to the function is made, the return address is pushed there too, by the processor. Inside the function, the stack pointer is stored and now the stack can also be used to store local variables. At the end of the function, the original stack pointer is restored (which makes the local variables invalid and inaccessible) and the processor pops the return address and continues with the code after the call. The caller code than removes the arguments from the stack and continues with the rest of its code.
FWIW, that is how it happens in C. There are other, similar schemes, where items are pushed on the stack in a different order or even passed in registers, or where the function clears the arguments from the stack. Such a scheme is called a calling convention. Obj-C uses the cdecl calling convention, which is more or less how I described it.

How exactly is NSPrintInfo's sharedPrintInfo shared?

Apple's documentation for NSPrintInfo states in part:
A shared NSPrintInfo object is automatically created for an application and is used by default for all printing jobs for that application.
The method sharedPrintInfo returns the shared NSPrintInfo. What's not explicitly stated is if you alter that object (e.g., by using setOrientation), do said alterations "stick" with the shared object? I.e., is the object you get back a singleton or a fresh copy of the shared object?
One reason I ask is because I've seen in some of Apple's sample code where they explicitly call setSharedPrintInfo at the end of a print job. Why do they do that if the shared object is a singleton?
Update
It seems I have to be clearer in my question. From Apple's documentation, there exists an instance of NSPrintInfo that is the "shared" one. This "shared" instance is used by default when no NSPrintInfo object is used explicitly in method calls. The method sharedPrintInfo returns a pointer to this "shared" instance.
What's not clear is whether sharedPrintInfo clones the "shared" instance and returns a pointer to that, or simply returns a pointer to the existing instance.
If cloned, then any call such as one to setOrientation will affect the clone only. If I wanted to alter the orientation of the "shared" instance also, I would have to call setSharedPrintInfo supplying the altered clone as an argument.
If not cloned, then it's not clear why Apple's sample code explicitly calls setSharedPrintInfo because all method calls altering the state of the NSPrintInfoObject returned by sharedPrintInfo already affected the "shared" instance.
What's not explicitly stated is if you alter that object (e.g., by using setOrientation), do said alterations "stick" with the shared object? I.e., is the object you get back a singleton or a fresh copy of the shared object?
Setters ordinarily return void; they don't return the object whose property you set. NSPrintInfo's setOrientation: method is one example.
Methods that return a copy of the receiver with the change applied say so explicitly in their name—for example, stringByAppendingString: (returns a modified copy), as opposed to appendString: (modifies the receiver).
So NSPrintInfo's setters only affect the object you send those messages to. If you send setOrientation: to the shared print info, you modify that object; you aren't creating a new print info.
OK, now for your actual question.
If you look at NSDocument, you'll see that each document can have its own print info. When the user enters Page Setup, they do so in a sheet on the document window, and their changes only affect that document—which is only possible by giving each document its own print info. If your app isn't document-based, it's probably a single-window app, and one print info for the whole process will do just fine.
The documentation for NSDocument calls out one specific case: You can override its printInfo method in your NSDocument subclass to always use the shared print info object. I can't imagine why you would do that, but in that case, the shared print info object is literally shared between all your open documents.
What's not clear is whether sharedPrintInfo clones the "shared" instance and returns a pointer to that, or simply returns a pointer to the existing instance.
In Cocoa, a sharedFoo method returns the shared foo object. It doesn't make a copy of it—that would defeat its purpose, which is to access the shared object.
This rule is also true of defaultFoo methods (e.g., [NSFileManager defaultManager]). Don't ask me why they call some of these methods defaultFoo and others sharedFoo. ☺
If you ever do want your own copy, many classes will let you make one; NSPrintInfo is one example that explicitly does allow this. Other classes (the shared panels in particular, such as NSColorPanel) exist in one and only one instance.
I don't know the answer to your question, but here's a simple test to find out: call sharedPrintInfo twice and compare the pointers. If they're the same, then no, you get the same NSPrintInfo object back each time. If they're different, then you get a different object back each time. You could do this in the debugger and have your answer in sixty seconds.
The NSPrintInfo documentation states the following, which seems pretty clear:
A shared NSPrintInfo object is automatically created for an application
and is used by default for all printing jobs for that application.
You can also initialize an instance of this class using the initWithDictionary: method.
You can use this dictionary to store custom information associated with a print job.
This would indicate that you can either use the shared object OR create your own.
Now to the second part of your question, why do the Apple examples call setSharedPrintInfo: ?
If you create your own using initWithDictionary: you CAN then store it to be the new shared one. But you don't have to.
source: Mac Dev Center, NSPrintInfo Class Reference
It's not a singleton. There's a shared NSPrintInfo object, because most apps only need one. You can also create additional NSPrintInfo instances if that's appropriate to your situation.

Objective C - Where do you dealloc global static variables?

Or, what is the opposite of +(void)initialize?
Here's my situation:
I have a class Unit, whose -(id)initWithName: function takes data from a global NSDictionary, which is created lazily, defined in the Unit.m file as:
static NSMutableDictionary *unitLibrary = nil;
Where do I call [unitLibrary release]?
You can call it at a location in which you know the dictionary is not needed anymore. If it is needed throughout the entire lifecycle of the application, then you don't have to do anything as all memories will be reclaimed by the OS when the app terminates.
There's no general-purpose answer. You should deallocate it when you're sure it won't be used again. Possible candidates might be in the applicationWillTerminate delegate message, or through an atexit() function.