Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to determinate at run time is pointer points to C++ class or at Objective-C class?

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]
}
like image 828
andrey.s Avatar asked Mar 08 '12 05:03

andrey.s


2 Answers

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.

like image 76
iammilind Avatar answered Nov 15 '22 05:11

iammilind


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.

like image 26
alexgolec Avatar answered Nov 15 '22 05:11

alexgolec