Question is in subject.
I want to write some universal template function for safe deleting objects and wondering is it possible to use something like this:
template< class T > void SafeDelete( T*& pVal )
{
if(objc_is_cpp_object(pVal)){
delete pVal;
pVal = NULL;
}
else
[pVal release]
}
As mentioned in comments, I would suggest not to mix the C++ delete
and Objective-C release
.
Just for technical point of view, you can use the following SFINAE trick runtime:
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];
}
}
Possibly, is_pod
is available in C++11, boost etc. But it's easy to implement.
Objective-C pointers are the same as C++ pointers: 4-to-8 word integer values that point to various objects in memory. The Objective-C compiler supports outputting values in with multiple formats, such as C, C++, and Objective-C object layouts.
That's it. There really isn't much beyond that.
You can try to do something hacky like create a class where a field always contains a magic value:
template <class T>
class Magic {
private:
const char magic[] = 1234567;
public:
bool is_object() const {
return magic == 1234567;
}
}
then you could test it like so:
bool is_cpp(void *ptr) {
return ((Magic*) ptr)->is_object();
}
But be forewarned that this is extremely hacky.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With