简体   繁体   中英

misconception about pointers C++

it seems that i have a misconception about pointers,

here is an example:(code may not compile,is on different PC)

#include <iostream>

struct Debris{
    long big_data;
    //code
};

struct Explosion{
    Debris *db;
    //code
};

void test(){
    Debris *db = new Debris();
    db->big_data = 10000;

    Explosion *e1 = new Explosion();

    e1->db = db;

    std::cout << "db addr:" << db <<"db value:"<< ++db->big_data <<<="" "explosion's="" db="" addr:"="" e1-="">db << "explosion's db value:" << e1->db->big_data << std::endl;

    //why db and e1->db have different addresses?
    //but the e1->db->big_data is changed by ref.
}

can you please explain this? thanks in advance.

When I fix the cout expression so it compiles, I see:

db addr:0x1378010 
db value:10001 
explosion's=0x1378010 
explosion's db value:10000

I assume you're asking why the value seems to be different, and you think should be the same in both cases. The pointers are the same, as one would expect since nothing changes them.

This is because you are both modifying and using the value in the same expression, without anything to sequence these actions. This gives the code undefined behaviour; you could see the old value, or the new value, or something completely unexpected could happen.

If you were to break it into two statements, then the first would be sequenced before the second and you would see the same value in each case:

std::cout << "db addr:" << db <<" db value:"<< ++db->big_data;
std::cout << " explosion's=" << e1->db << " explosion's db value:" << e1->db->big_data << std::endl;

db addr:0x1720010 
db value:10001 
explosion's=0x1720010 
explosion's db value:10001

The fact that you incremented db accounts for the change. ++ is high priority among the operators. Add parentheses if your intent was to instead increment big_data before using the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM