我正在玩我的智能指针类,我想实现具有以下行为的++ 和 -- 运算符:如果指针指向单个变量或者它指向数组并且++(--) 将指针移出数组尝试++(--) 时应抛出异常。
类似的东西:
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
我尝试使用 typeid。但无论如何它都会返回 A 类型。
A* arr=new A[3];
typeid(arr).name();//type is P1A
typeid(--arr).name();//type is P1A
typeid(arr+7).name();//type is P1A
那么有什么方法可以确定指针在++(--) 之后是否指向“我的”类型的对象?
最佳答案
new A[3]
返回一个 A*
,就像 new A
一样。所以你无法区分它们。
如果您希望您的类进行边界检查,那么您需要明确地告诉它数组中有多少项。
关于c++ - 如何确定对象指针指向的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9053919/