首页 > 其他 > 详细

Why am I getting an error converting a Foo** → const Foo**?

时间:2015-12-21 18:32:20      阅读:234      评论:0      收藏:0      [点我收藏+]

Because converting Foo**const Foo** would be invalid and dangerous.

C++ allows the (safe) conversion Foo*Foo const*, but gives an error if you try to implicitly convert Foo**const Foo**.

The rationale for why that error is a good thing is given below. But first, here is the most common solution: simply change const Foo** to const Foo* const*:

  1. class Foo { /* ... */ };
  2. void f(const Foo** p);
  3. void g(const Foo* const* p);
  4. int main()
  5. {
  6. Foo** p = /*...*/;
  7. // ...
  8. f(p); // ERROR: it‘s illegal and immoral to convert Foo** to const Foo**
  9. g(p); // Okay: it‘s legal and moral to convert Foo** to const Foo* const*
  10. // ...
  11. }

The reason the conversion from Foo**const Foo** is dangerous is that it would let you silently and accidentally modify a const Foo object without a cast:

  1. class Foo {
  2. public:
  3. void modify(); // make some modification to the this object
  4. };
  5. int main()
  6. {
  7. const Foo x;
  8. Foo* p;
  9. const Foo** q = &p; // q now points to p; this is (fortunately!) an error
  10. *q = &x; // p now points to x
  11. p->modify(); // Ouch: modifies a const Foo!!
  12. // ...
  13. }

If the q = &p line were legal, q would be pointing at p. The next line, *q = &x, changes p itself (since *q is p) to point at x. That would be a bad thing, since we would have lost the const qualifier: p is a Foo* but x is a const Foo. The p->modify() line exploits p’s ability to modify its referent, which is the real problem, since we ended up modifying a const Foo.

By way of analogy, if you hide a criminal under a lawful disguise, he can then exploit the trust given to that disguise. That’s bad.

Why am I getting an error converting a Foo** → const Foo**?

原文:http://www.cnblogs.com/hustxujinkang/p/5064050.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!