1

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";
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Chenna V
  • 10,185
  • 11
  • 77
  • 104

4 Answers4

18

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.

Kos
  • 70,399
  • 25
  • 169
  • 233
  • Well-put and very concise. +1 – Martin Törnwall Nov 29 '10 at 21:09
  • 1
    The only thing I would add is that the compiler may munge around placement of subsequent members in an attempt to keep the object aligned in memory. This is called padding, and makes this kind of type punning even more dangerous, particularly because it may vary depending on compiler pragmas or flags. Pack(1) will work on many compilers to turn padding off. Don't do this, things are padded for some very good reasons. Unless you can articulate those reasons, and a counter-argument specific to your use case, you do not need Pack(1). – Jake Kurzer Nov 29 '10 at 23:12
1

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.

rtpg
  • 2,419
  • 1
  • 18
  • 31
0

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.

Ronnie Howell
  • 639
  • 3
  • 8
0

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

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124