Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to detect whether the pointer points to array?

Is there any way to detect, whether the pointer points to array in C++? My problem is that I want to implement a class, that becomes the owner of the array. My class is initialized with the pointer and I would like to know, whether the pointer is really an array pointer. Here is the simplified code:

class ArrayOwner {
public:
   explicit ArrayOwner( int* initialArray ) : _ptrToArray(initialArray) {}
   virtual ~ArrayOwner() { delete [] _ptrToArray; }
private:
   int* _ptrToArray;
}
  • This usage will be ok: ArrayOwner foo( new int[10] );
  • But this usage leads to undefined behaviour: ArrayOwner foo( new int() );

I would like to add assert in the constructor, that the "initialArray" pointer is really an array pointer. I cannot change the contract of the constructor, use vectors e.t.c. Is there any way to write this assert in C++?

like image 470
SadSido Avatar asked Dec 05 '22 05:12

SadSido


1 Answers

No, unfortunately not. C++ RTTI does not extend to primitive types.

like image 194
Binary Worrier Avatar answered Dec 21 '22 11:12

Binary Worrier