禁用类指针递增/递减运算符
例如代码:
A* pA = new A;
我需要在编译阶段避免指针递增/递减运算符:
pA++; // MUST failed during compilation phase
For example code:
A* pA = new A;
I need to avoid pointer increment/decrement operators during compilation phase:
pA++; // MUST failed during compilation phase
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 pA 声明为
这使得 pA 成为指向 A 对象的 const 指针。初始化后指针无法更改,但其内容可以。
比较
它是一个指向 const A 对象的指针。
如果要迭代 A 对象的数组,请获取单独的指针。
You could declare pA as
This makes pA a const pointer to an A object. The pointer cannot be changed after initialisation, but the contents of it can.
compare
which is a pointer to a const A object.
If you want to iterate over an array of A objects get a separate pointer.
这是不可能的。
因为我猜你想这样做是为了避免意外错误,所以我猜智能(ass)解决方案不适用(包括发明一些类似指针的包装类等),因为它们会增加错误的可能性:)
That's impossible to do.
Since I guess you want to do that to avoid unintended errors, I guess smart(ass) solutions do not apply (including inventing some pointer-like wrapper classes etc) because they will increase the probability of errors :)
如果你想坚持使用原始指针,这是不可能的。
您需要用一个不实现该运算符(也称为智能指针)的类来包装它。
If you want to stick with raw pointers, it's impossible.
You need to wrap it with a class that doesn't implement that operators (aka smart pointers).