Lev
Lev

Reputation: 1930

pointers to compare objects for equality c++

Since pointers are integers, the idea is that if

Object* one = new SameObject();
Object* two = one;

then if I compare one to two, I will get true.

Can I use this to compare two such objects for equality? Can this be used as a guarantee of equality? Are objects moved in the heap at any point after initialization?

Upvotes: 1

Views: 838

Answers (2)

Barmar
Barmar

Reputation: 780798

If you're comparing global or static variables, no two variables can have the same address, and they're never moved. So if the addresses are equal, the pointers must refer to the same variables, and the values will be equal.

For local variables, this will only be true as long as you have not returned from the function that declared the variables. The addresses of local variables are only valid while that function call is in progress. It's very possible that after you return from one function, and then call some other function, that the address of a variable in the first function may compare equal to a variable in the second function. Any use of addresses of variables from a function that has returns results in undefined behavior.

Similarly, the address of a heap-allocated object (created with new or malloc()) will only be valid until the object is deleted (with delete or free()). Heap objects are not moved (or if they are, it should be transparent to the program). But if you delete an object, and then create a new object, the new object could get the address of the deleted one.

Upvotes: 1

Anon Mail
Anon Mail

Reputation: 4770

Can I use this to compare two such objects for equality?

It's not recommended. Because equality is generally not construed to mean "it's the same object". Two different integers (occupy different memory addresses) that both contain the value 4 are considered equal.

Can this be used as a guarantee of equality?

No, as explained above

Are objects moved in the heap at any point after initialization?

It's not clear what you mean here. But I think what you mean is an object, once created on the heap, does it ever move. The answer is, yes. For example, if you keep inserting objects into a std::vector via push_back(). Since a vector's items must be contiguous, if it runs out of space, it will allocated a new bigger space and copy all the old values into the new space. So, yes, all of those heap allocated objects will now be in a new location.

Upvotes: 4

Related Questions