码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-12-21 18:34:24      阅读:162      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!