I have a question:
I don’t explicitly “new” and “delete” my C++ instance, but it automatically calls “new” and “delete” when the objective-c class init. Any idea?
class myCppTestClass
{
public:
myCppTestClass()
{
NSLog(@"MyCpp constructor");
}
~myCppTestClass()
{
NSLog(@"MyCpp destructor");
}
};
@interface MyTestClass : NSObject
{
myCppTestClass myCppInstance;
}
@end
@implementation MyTestClass
@end
And I call it like this:
NSLog(@"Create an object.");
MyTestClass *objcObject = [[MyTestClass alloc] init];
NSLog(@"Object created");
[objcObject release];
objcObject = nil;
NSLog(@"Object released.");
Then I run it, the log is like this:
2012-11-16 12:01:18.747 iOSVersion[87248:f803] Create an object.
2012-11-16 12:01:18.749 iOSVersion[87248:f803] MyCpp constructor
2012-11-16 12:01:18.750 iOSVersion[87248:f803] Object created
2012-11-16 12:01:18.751 iOSVersion[87248:f803] MyCpp destructor
2012-11-16 12:01:18.752 iOSVersion[87248:f803] Object released.
It’s not about Automatic Reference Counnting, because it is closed, any ideas? Thank you so much.
Again, if MyTestClass is like this, the constructor and destructor will not been called:
@interface MyTestClass : NSObject
{
myCppTestClass * myCppInstance;
}
and the log:
2012-11-16 12:22:38.710 iOSVersion[87428:f803] Create an object.
2012-11-16 12:22:38.711 iOSVersion[87428:f803] Object created
2012-11-16 12:22:38.712 iOSVersion[87428:f803] Object released.
The language does not
newanddeletefor you, but it calls the constructor and destructor. This is the standard behavior of C++: when you create an object, directly or indirectly, the constructor for the contained object gets called; similarly, when the containing object gets deallocated, the destructors of all contained instances get called as well.