zoukankan      html  css  js  c++  java
  • Why am I getting an error converting a Foo** → const Foo**?

    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.

  • 相关阅读:
    .Net常用的命名空间
    Jquery测试纠错笔记
    第一章 学习总结
    Java和C++引用的区别
    gin的墙内开发艺术
    golang几个环境变量的问题
    Leetcode240_搜索二维矩阵II
    Leetcode1358_包含所有三种字符的子字符串数目
    Leetcode1354_多次求和构造目标数组
    Leetcode1353_最多可以参加的会议数目
  • 原文地址:https://www.cnblogs.com/hustxujinkang/p/5064050.html
Copyright © 2011-2022 走看看