In C++, checking whether two pointers reference the same object is relatively straightforward. When verifying if two pointers point to the same memory address, we can directly compare them using the equality operator (==).
Example Code:
cpp#include <iostream> class Example { public: int value; Example(int v) : value(v) {} }; int main() { Example a(10); Example b(20); Example* ptr1 = &a; Example* ptr2 = &a; Example* ptr3 = &b; if (ptr1 == ptr2) { std::cout << "ptr1 and ptr2 point to the same object." << std::endl; } else { std::cout << "ptr1 and ptr2 do not point to the same object." << std::endl; } if (ptr1 == ptr3) { std::cout << "ptr1 and ptr3 point to the same object." << std::endl; } else { std::cout << "ptr1 and ptr3 do not point to the same object." << std::endl; } return 0; }
In this example, ptr1 and ptr2 both reference object a, resulting in identical addresses and a true comparison. ptr3 references object b, which has a different address from ptr1, leading to a false comparison.
This approach is the most straightforward and commonly used method for verifying whether two pointers reference the same object. Note that this comparison evaluates the address values of the pointers, not the content of the objects they reference. For comparing object contents, you should perform an object-level comparison rather than a simple pointer comparison.