1.17.  const* and *const

[ fromfile: constptrs.xml id: constptrs ]

  1. If you want to make sure that ptr cannot point to any other memory location (i.e., cannot store a different address), you can write it one of two ways:

    Type* const ptr = &vbl;
    Type* const ptr(&vbl);
    
    • If you want to make sure that the value of vbl cannot be changed by dereferencing ptr, you can write it in two ways:

    const Type* ptr = &vbl;
    const Type* ptr(&vbl);
    
      • If you want to impose both kinds of protection you can write:

        const Type* const ptr = &vbl;
        const Type* const ptr(&vbl);
        

    Example 1.30. src/constptr/constptr.cpp

    #include <QTextStream>
    
    int main() {
        QTextStream cout(stdout);
        int m1(11), m2(13);
        const int* n1(&m1);
        int* const n2(&m2);
        // First snapshot
        cout << "n1 = " << n1 << '\t' << *n1 << '\n'
             << "n2 = " << n2 << '\t' << *n2 << endl;
        n1 = &m2;
        //*n1 = 15; 1
        m1 = 17;    2
        //n2 = &m1; 3
        *n2 = 16;   4
        // Second snapshot
        cout << "n1 = " << n1 << '\t' << *n1 << '\n' 
             << "n2 = " << n2 << '\t' << *n2 << endl;
        return 0;
    }
    Output:
    
    src/constptr> ./constptr
    n1 = 0xbffff504 11
    n2 = 0xbffff500 13
    n1 = 0xbffff500 16
    n2 = 0xbffff500 16
    src/constptr>
    
    
    
    

    1

    Error: assignment of read-only location

    2

    m2 is an ordinary int variable, okay to assign

    3

    Error: assignment of read-only variable 'n2'

    4

    Okay to change target


    Figure 1.5.  Memory Snapshots

    Memory Snapshots
    Memory Snapshots