Created
May 8, 2013 12:23
-
-
Save iamleeg/5540103 to your computer and use it in GitHub Desktop.
Creating objects on the stack, ObjC++ style.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface GLObject : NSObject | |
{ | |
int _a; | |
} | |
- (void)logA; | |
@end | |
struct GLObject_cpp { | |
Class isa; | |
int _a; | |
GLObject_cpp() | |
: _a(30), | |
isa([GLObject class]) | |
{} | |
public: | |
void giveMeaning() { this->_a = 42; } | |
}; | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
struct GLObject_cpp cppObj = GLObject_cpp(); | |
id obj = (__bridge id)(&cppObj); | |
NSLog(@"obj: %@", obj); | |
cppObj.giveMeaning(); | |
[obj logA]; | |
} | |
return 0; | |
} | |
@implementation GLObject | |
- (NSString *)description { return [NSString stringWithFormat: @"GLObject <%p>: %d", self, _a]; } | |
- (void)logA { NSLog(@"In %p, _a = %d", self, _a); } | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One (last) observation:
-dealloc
won't be called. This is good in that it means NSObject's-dealloc
implementation won't try to release the memory (which would probably cause a crash), but bad in that it means that some classes wouldn’t clear up properly after themselves.