views:

218

answers:

5

Hi, everyone!

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++?

+4  A: 

There's no portable way to do it.

Drakosha
+4  A: 

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

Binary Worrier
A: 

Generally, there is no (simple/portable/robust) way to do that.

Having said that, if you know your platform and you're willing to change your code for every new version of the OS, you might be able to find out where the heaps are and how they look like, so you may want to walk the heap and see the size of the block which this pointer points to, so you can calculate the number of items there. But everyone will advice you against doing that.

Rom
A: 

I don't think so. x[] and *x are synonyms except, of course, when you call delete on them.

Aaron Digulla
+3  A: 

It looks like a bad design to me. Don't separate new and delete this way.

The array should be allocated in the object constructor, not passed as a parameter.

Memory management in C++ is hard, don't make it harder with bad practice like this.

Alexis Bietti
He's trying to implement "initialization is resource acquisition" (look here http://www.ddj.com/cpp/184403758)
Drakosha
Then he should acquire the resource in the constructor. That is the only way he can be certain that _ptrToArray points to an array.
Treb
As I have mentioned in the comments to the question itself, there is an interaction with the client script. Scripters expect the array wrapper, that can be initialized like ArrayOwner( int* array ). p.s. Undoubtfully a bad design, but we don't have a direct control over the scripts. We can only force the scripters to pass exactly *arrays* by introducing a coding convention...
SadSido