简体   繁体   English

指向对象的指针==指向第一个成员的指针?

[英]pointer to object == pointer to first member?

Why does the if condition in the following code yield true? 为什么以下代码中的if条件产生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: 在阅读关于空类的Stroustrup的FAQ时,我有些困惑,尤其是下面的语句:

if (p1 == p2) cout << "nice: good optimizer";

There are no references involved in your code. 您的代码中没有引用。 Don't confuse the "address-of" operator (also & ) with references. 不要将“ address-of”运算符(以及& )与引用混淆。

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. 您的条件返回true,因为在这种情况下,恰好该对象与它的第一个(也是唯一一个)字段在内存中的同一位置开始。 That's the case ie for so-called POD (plain-old-data) objects, but it's not always true. 就是这种情况,即所谓的POD(普通数据)对象,但并非总是如此。

For example it's likely for the condition to be false if your class contains any virtual functions. 例如,如果您的类包含任何虚函数,则条件可能为假。 Don't depend on it. 不要依赖它。

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. 在这里,a1是仅包含firstMember的类,因此内存中的结构就是该元素:内存中a1的开头与firstMember的开头相同。

A reference acts much like a pointer in C++. 引用的行为很像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. 在这种情况下,您正在将a1中的第一条信息与a1本身进行比较。 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. 特别是在64位OS中,编译器可能会调整地址以解决内存中的对齐问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM