我有一个问题:为什么C++实例在通过Objective-c类调用时自动调用构造函数和析构函数?
我没有明确“new
”和“delete
”我的C++实例,但是它会自动调用“new
”和“delete
”的时候,Objective-C类初始化。任何想法?
class myCppTestClass
{
public:
myCppTestClass()
{
NSLog(@"MyCpp constructor");
}
~myCppTestClass()
{
NSLog(@"MyCpp destructor");
}
};
@interface MyTestClass : NSObject
{
myCppTestClass myCppInstance;
}
@end
@implementation MyTestClass
@end
我这样称呼它:
NSLog(@"Create an object.");
MyTestClass *objcObject = [[MyTestClass alloc] init];
NSLog(@"Object created");
[objcObject release];
objcObject = nil;
NSLog(@"Object released.");
然后我运行它,日志是这样的:
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.
这不是自动引用Counnting,因为它是封闭, 有任何想法吗?非常感谢。
同样,如果MyTestClass是这样的,构造函数和析构函数不会被调用:
@interface MyTestClass : NSObject
{
myCppTestClass * myCppInstance;
}
和日志:
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.
它的时候都没有指针或引用C++对象是如何工作的。 –
你的意思是'myCppTestClass myCppInstance;'? – lijinma
是的,变量声明通过一些运行时向导来分配对象时调用缺省构造函数。 –