比较C和C ++中的结构 [英] Comparing structures in C vs C++

查看:126
本文介绍了比较C和C ++中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较C ++类/结构对象。在C中,大多数时候,通过将各个字段的大小相加(假设编译器不添加填充),可以知道 struct 的精确大小。因此,可以对两个对象使用memcmp()函数来比较它们非常快。我不知道是否同样适用于C ++。这是因为一个类也有函数定义和一些其他隐藏的东西(一些RTTI信息可能?虚拟函数表甚至?)

I want to compare C++ class/structure objects. In C, most of the time, one knows exact size of the struct by adding up the sizes of individual fields (assuming that compiler does not add padding). Hence one can use memcmp() function on two object to compare them very fast. I am not sure if the same works for C++. This is because a class also has function definitions and maybe some other hidden things (some RTTI info perhaps? A virtual function table even?)

一个简单的结构的快速程序包含 int char 成员和一个函数显示结构的大小 sizeof )+ sizeof(char)

A quick program with a simple structure containing int and char members and a function showed that size of the structure was sizeof(int)+sizeof(char).

我有一个大的结构类,包含简单的int,char等数据类型他们)。我想不时地比较对象。我不能重载 == 运算符,因为这将使他们按字段比较每个字段。在C中,我可以使用 memcmp()进行比较。任何建议C ++?我可以直接使用 memcmp()吗?我不想让memcmp()失败,因为一些其他值像虚函数指针表是不同的(但所有字段实际上是相等的)
(我使用g ++)

I have a one big struct class with simple int, char etc data types (but a large number of them). I want to compare objects from time to time. I cannot overload the == operator as that will make them compare each field by field. In C, I can compare in one go using memcmp(). Any suggestions for C++? Can I use memcmp() directly? I dont want memcmp() to fail because some other value like virtual function pointer table is different (but all the fields are actually equal) (I'm using g++)

推荐答案

对许多计数要小心...

Be wary on numerous counts...



  1. 如果你的机器是little-endian,比较整数字段将产生一个答案;如果你的机器是big-endian,它会产生另一个答案。

  2. 大多数人认为-1小于0,但 memcmp()将执行字节无符号比较,因此将处理-1大于0。

  3. 任何指针本质上不能由 memcmp / code>。

  4. 您不能比较 float double 使用 memcmp()

  1. The values in any padding is indeterminate and hence not comparable.
  2. If your machine is little-endian, comparing integer fields will produce one answer; if your machine is big-endian, it will produce another answer.
  3. Most people regard -1 as smaller than 0, but memcmp() will do byte-wise unsigned comparison, and will therefore treat -1 as bigger than 0.
  4. Any pointers are inherently not comparable relevantly by memcmp().
  5. You cannot compare float or double using memcmp().

- 优化。

这篇关于比较C和C ++中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆