简体   繁体   中英

C++ Pointer Comparison

How pointers are compared in C++?

The last line in the following code shows that values of b and c are different. However, b==c returns true.

#include <iostream>

struct A { int a; };
struct B { int b; };
struct C : A, B { };

int main() {
    auto c = new C();
    B* b = static_cast<B*>(c);
    A* a = static_cast<A*>(c);
    a->a = 1;
    b->b = 2;
    std::cout << c->a << c->b <<"\n";
    std::cout << (a==c) << (b==c) << "\n";
    std::cout << (long)a << "\n" << (long)b << "\n" << (long)c <<"\n";
}

A sample output that I received using GCC and Clang:

12
11
34073632
34073636
34073632

Don't cast pointers to long, cast them to intptr_t.

    std::cout << (intptr_t)a << "\n" << (intptr_t)b << "\n" << (intptr_t)c <<"\n";

Anyhow, see this definition:

struct C : A, B { };

in memory that would look like:

{
  A; [sizeof int]
  B; [sizeof int]
}

Since A and B are both base classes of C, when you do this:

    A* a = static_cast<A*>(c);

You get a pointer to the first 4 bytes of C. When you do this:

    B* b = static_cast<B*>(c);

You get a pointer to the last 4 bytes of C, hence the difference. A pointer to type C will always implicitly cast the pointer this way.

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