获取 class 变量和 class 对象的起始地址之间的地址差异的最佳方法是什么?
What's the best way to get address difference between a class variable and the starting address of a class object?
需要为 class 数据成员生成唯一键。因此,我正在考虑获取变量地址减去 class 对象地址之间的差值。例如:
struct X {
int i; // &i - &X() = 0 (GCC)
double d; // &d - &X() = 8 (GCC)
};
这是一次性练习,因此将在所有感兴趣的 classes 的代码执行的最开始进行。所以通常我会声明一个 class 的虚拟对象并通过类型转换找到地址差异。如:
X x;
keyOf_i = long(&x.i) - long(&x);
keyOf_d = long(&x.d) - long(&x);
有没有更好的方法?
假设访问说明符 (private
) 不是问题。
如果有人有除此之外的任何其他方法为 class 数据变量生成唯一键,也会感兴趣。
更新:使用offseof()
宏,我在G++-6中收到以下警告:
offsetof within non-standard-layout type ‘MyClass’ is undefined
实际上我在 MyClass
中还有一些字符串和其他 class 变量。我很好,即使这个未定义的东西提供了唯一的地址。但是,想获得 offsetof()
和其他替代方案的更多信息。
为此使用 offsetof() 宏如何?查看 http://man7.org/linux/man-pages/man3/offsetof.3.html 了解更多详情。
手册页中的示例代码如下:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct s {
int i;
char c;
double d;
char a[];
};
/* Output is compiler dependent */
printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
(long) offsetof(struct s, i),
(long) offsetof(struct s, c),
(long) offsetof(struct s, d),
(long) offsetof(struct s, a));
printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
exit(EXIT_SUCCESS);
}
需要为 class 数据成员生成唯一键。因此,我正在考虑获取变量地址减去 class 对象地址之间的差值。例如:
struct X {
int i; // &i - &X() = 0 (GCC)
double d; // &d - &X() = 8 (GCC)
};
这是一次性练习,因此将在所有感兴趣的 classes 的代码执行的最开始进行。所以通常我会声明一个 class 的虚拟对象并通过类型转换找到地址差异。如:
X x;
keyOf_i = long(&x.i) - long(&x);
keyOf_d = long(&x.d) - long(&x);
有没有更好的方法?
假设访问说明符 (private
) 不是问题。
如果有人有除此之外的任何其他方法为 class 数据变量生成唯一键,也会感兴趣。
更新:使用offseof()
宏,我在G++-6中收到以下警告:
offsetof within non-standard-layout type ‘MyClass’ is undefined
实际上我在 MyClass
中还有一些字符串和其他 class 变量。我很好,即使这个未定义的东西提供了唯一的地址。但是,想获得 offsetof()
和其他替代方案的更多信息。
为此使用 offsetof() 宏如何?查看 http://man7.org/linux/man-pages/man3/offsetof.3.html 了解更多详情。
手册页中的示例代码如下:
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct s {
int i;
char c;
double d;
char a[];
};
/* Output is compiler dependent */
printf("offsets: i=%ld; c=%ld; d=%ld a=%ld\n",
(long) offsetof(struct s, i),
(long) offsetof(struct s, c),
(long) offsetof(struct s, d),
(long) offsetof(struct s, a));
printf("sizeof(struct s)=%ld\n", (long) sizeof(struct s));
exit(EXIT_SUCCESS);
}