Question

Why does the if condition in the following code yield true?

struct A
{
    int firstMember;
} a1;

if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";

I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:

if (p1 == p2) cout << "nice: good optimizer";
Was it helpful?

Solution

There are no references involved in your code. Don't confuse the "address-of" operator (also &) with references.

Your condition returns true because in this case it happens that the object starts in the same place in memory as its first (and only) field. That's the case i.e. for so-called POD (plain-old-data) objects, but it's not always true.

For example it's likely for the condition to be false if your class contains any virtual functions. Don't depend on it.

OTHER TIPS

the reference operator sends back a pointer to the memory address which contains the member.

Here, a1 is a class containing only firstMember, so the in-memory structure is just that element: the beginning of a1 in memory is the same as the beginning of firstMember.

A reference acts much like a pointer in C++. When you take the reference to a variable, you are asking for the location in memory for that variable. In this case, you are comparing the first piece of information in a1 to a1 itself. This is a specific case where this will work, and isn't something you should rely on.

Yes, you cannot depend on it. Especially, in 64 bit OS, compiler may adjust the addresses to account for alignment in memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top