Skip to content

Instantly share code, notes, and snippets.

@iamleeg
Created May 8, 2013 12:23
Show Gist options
  • Save iamleeg/5540103 to your computer and use it in GitHub Desktop.
Save iamleeg/5540103 to your computer and use it in GitHub Desktop.
Creating objects on the stack, ObjC++ style.
@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
@al45tair
Copy link

al45tair commented May 9, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment