Consider this code example:
class SomeArbitrarilyNamedClassPlusPlus {
public:
SomeArbitrarilyNamedClassPlusPlus(NSObject *object) { object_ = object; }
SomeArbitrarilyNamedClassPlusPlus() { object_ = nil; }
private:
NSObject *object_;
};
@interface SomeArbitrarilyNamedClassObjective : NSObject
{
SomeArbitrarilyNamedClassPlusPlus *_plusPlusObject;
}
@end
@implementation SomeArbitrarilyNamedClassObjective
-(id)init
{
if ((self = [super init]))
{
_plusPlusObject = new SomeArbitrarilyNamedClassPlusPlus(self);
}
return self;
}
-(void)dealloc
{
NSLog(@"deallocated");
delete _plusPlusObject;
}
@end
int main(int argc, const char * argv[])
{
{
SomeArbitrarilyNamedClassObjective *object = [[SomeArbitrarilyNamedClassObjective alloc] init];
}
return 0;
}
The object
variable never gets deallocated. You can check it with Instruments - additional retain counter increment happens inside the -(id)init
call.
I would never expect that attributes in C++ classes are strong and this makes me wondering - is there a way to make c++ attributes pointing on Objective-C objects weak?
UPDATE:
There is a way to avoid this using pointers to void
in C++ class instead of NSObject*
and initialize C++ class in -(id)init
method like that:
...
_plusPlusObject = new SomeArbitrarilyNamedClassPlusPlus((__bridge void*)self);
...
However, the question still remains - is there a way to save Objective-C types inside C++ classes but make them weak?