licoded / self-study-drafts

buffer for records
0 stars 0 forks source link

Amazing CPP: const is just a limit for modification? #147

Open licoded opened 11 months ago

licoded commented 11 months ago
#include <iostream>

int main()
{
    // const int * const p = new int(10);
    // const int * p1 = new int(10);
    int * const p2 = new int(10);
    const int * const p2_copy = p2;

    std::cout 
            << "p2 = " 
            << (*p2) << std::endl;
    std::cout 
            << "p2_copy = " 
            << (*p2_copy) << std::endl;

    *p2 = 11;

    std::cout
        << "after modification of *p2 = 11"
        << std::endl;

    std::cout 
            << "p2 = " 
            << (*p2) << std::endl;
    std::cout 
            << "p2_copy = " 
            << (*p2_copy) << std::endl;
    return 0;
}

运行结果:

PS D:\files\23.10_lyk\cpp_learn_tests> g++ .\01.const\main.cpp
PS D:\files\23.10_lyk\cpp_learn_tests> .\a.exe
p2 = 10
p2_copy = 10
after modification of *p2 = 11
p2 = 11
p2_copy = 11