Reputation: 779
Im playing with my smart pointer class and I want to implement ++ and -- operators with the following behavior: If pointer points to single variable or if it points to array and ++(--) moves pointer out of array bounds an exception should be thrown when trying to ++(--).
Something like that:
class A;
SmartPtr<A> s(new A[3]);
SmartPtr<A> s1(new A());
++s;//ok
--s;//ok
--s;//exception OutOfBounds thrown
++s1;//exception OutOfBounds thrown
--s1;//exception OutOfBounds thrown
I tried to use typeid. But it returns A type anyway.
A* arr=new A[3];
typeid(arr).name();//type is P1A
typeid(--arr).name();//type is P1A
typeid(arr+7).name();//type is P1A
So is there any way to determine does pointer point to "my" type of object after ++(--)?
Upvotes: 1
Views: 184
Reputation: 52679
stop using raw pointers/raw arrays and start using a vector. Then you can get the size of the vector and simply store the position of the element in your smart pointer class.
Upvotes: 1
Reputation: 13973
You can only do this kind of bounds checking if you use a utility function, rather than array new
directly, e.g.:
template <class Type, std::size_t size>
SmartPtr<Type> MakeArrayPtr()
{
return SmartPtr<Type>(new Type[size], size);
}
If the smart pointer deletes the object, remember to have it use delete[]
in the case of arrays.
Upvotes: 1
Reputation: 1006
No, if you want to implement this kind of behaviour, you must store somewhere the size of the allocated array.
Upvotes: 1
Reputation: 272497
new A[3]
returns an A*
, just like new A
does. So you can't distinguish them.
If you want your class to do bounds checking, then you will need to explicitly tell it how many items are in the array.
Upvotes: 3