简体   繁体   中英

Pointer to integer using reinterpret

I'm trying to cast a pointer to another type using reinterpret_cast

class MyClassA
{
 int x;
 int y;
 public:
    MyClassA();
    ~MyClassA();
};

class MyClassB
{
 int x;
 int y;
 public:
    MyClassB();
    ~MyClassB();
};

For example, if I cast a pointer to MyClassA to MyClassB, using reinterpret_cast would this conversion work? what about code portability?

And also, as I noted:

(5.2.10/4) A pointer can be explicitly converted to any integral type large enough to hold it.

Does it mean any pointer eg MyClassA* can only be converted to int* pointer? if i'm correct?

As to whether this works or not I do not know, that would be implementation dependant.

However there are no guarantee by the standard that this would work (so don't do it), MyClassA and MyClassB are two separate types that are non compatible even if they are structurally the same.

Same applies to int*.

if you need conversion between then then you can make an A to B assignment operator

class MyClassA{
...

    operator=(const MyClassB& mcb)
    {
        this.x=mcb.x;
        this.y=mcb.y;
    }
};

And if you need access to an integer element inside of MyClassA.

//in MyClassA
int& getX(){ return x; }
const int& getX() const { return x; }

int& x=mca.getX();

(5.2.10/4) A pointer can be explicitly converted to any integral type large enough to hold it.

This means int* to int . Pointers aren't integral types.

Casting pointers of unrelated types is bad news and shouldn't be done. It may work, but is not portable.

Inheritance will work though. Have the types inherit from a base class!

That doesn't mean you can cast unrelated types. It means you can cast a pointer to a 64bit integer (for example) if on your platform 64bit integer is sufficiently big enough to contain a pointer value.

PS: I would like to mention that what you have done is totally deviating from the standard but you might get away with it on many platforms / compilers :)

My answer to the first is yes. A pointer is just a variable (integral) whose value is an address to another memory location. Which is why you are able to do the following.

(*(void(*)())0)(); /*Ref: Andrew Koenig C Traps and Pitfals*/

or

#define CARD_INTERFACE_ADDRESS 0x4801C
struct A * = new (CARD_INTERFACE_ADDRESS) struct A

MyClassA * ptr_a cannot (logically) be converted to int* ptr_i because what you are saying is that the the address held by the variable ptr_a is the address of MyClassA in the former while in the latter you are saying that saying that ptr_i is the address of an int .

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