问题在主题中。
我想编写一些用于安全删除对象的通用模板函数,想知道是否可以使用这样的函数:
template< class T > void SafeDelete( T*& pVal )
{
if(objc_is_cpp_object(pVal)){
delete pVal;
pVal = NULL;
}
else
[pVal release]
}
最佳答案
如评论中所述,我建议不要混合使用 C++ delete
和 Objective-C release
。
仅出于技术角度,您可以使用以下 SFINAE 技巧运行时:
template<typename T> struct void_ { typedef void type; };
template<typename, typename = void>
struct CppType { static const bool value = false; };
template<typename T>
struct CppType<T, typename void_<int (T::*)>::type> { static const bool value = true; };
template< class T >
void SafeDelete( T*& pVal )
{
if(CppType<T>::value || std::is_pod<T>::value) { // <-----
delete pVal;
pVal = 0;
}
else {
// [pVal release];
}
}
is_pod
可能在 C++11、boost 等中可用。但它很容易实现。
关于c++ - 是否可以在运行时确定指针指向 C++ 类还是指向 Objective-C 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9613192/