我使用 C++ 作为应用程序主干,使用 Objective-C 作为 GUI,这很好。
但是当谈到在 Objective-C++(.mm 文件)中将这些代码混合在一起时,我有几个问题:
1. 我可以将 STL 容器与 Objective-C 或 Cocos2D 对象混合使用吗?
例如。在 Objective-C 标头中,我可以执行以下操作吗?
#include <vector>
#include <boost\shared_ptr.hpp>
@interface MyClass : NSObject {
std::vector<boost::shared_ptr<CCSprite> > m_spriteList;
}
然后在.mm
文件,我想做
CCSprite* newSprite = [/* cocos2d stuff here... */];
m_spriteList.push_back(newSprite);
上述代码有效吗?它当然是在 C++ 中,但我不确定何时混合 C++ 和 Objective-C 和 Cocos2D。
2. Objective-C中使用C++智能指针对象进行内存管理?
当我尝试在 Objective-C 中使用 C++ 代码时,我想在 Objective-C 头文件中声明一个 C++ 对象作为成员变量。
假设我有一个 C++ 类声明在test.h
header:
Test{
};
在 Objective-C 头文件中,我想做
#include "test.h"
#incude <boost/scoped_ptr.hpp>
#include <vector>
@interface MyClass : NSObject {
Test* m_testObjectPtr; // (1)
boost::scoped_ptr<Test> m_testOjbSmartPtr; // (2)
}
上面的代码中,(2)可以吗?我可以像在 C++ 代码中一样在 Objective-C 中使用智能指针吗?我可以假设Test
当类的析构函数被调用时MyClass
对象被破坏?
或者,如果 (2) 在 Objective-C++ 中不行,那么 (1) 可以吗?我需要手动调用吗delete m_testObjectPtr
in dealloc
?