内存中 C++ 对象的结构与结构 [英] Structure of a C++ Object in Memory Vs a Struct

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

问题描述

如果我有一个类如下

   class Example_Class 
   {
       private:
         int x; 
         int y; 
       public: 
         Example_Class() 
         { 
             x = 8;
             y = 9;
         }
       ~Example_Class() 
       { } 
   };

结构如下

struct
{
   int x;
   int y;
} example_struct;

example_struct在内存中的结构是否与Example_Class

例如,如果我执行以下操作

for example if I do the following

struct example_struct foo_struct;
Example_Class foo_class = Example_Class();

memcpy(&foo_struct, &foo_class, sizeof(foo_struct));

foo_struct.x = 8foo_struct.y = 9(即:与 foo_class 中的 x,y 值相同的值)?

will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ?

我问的原因是我有一个 C++ 库(不想更改它),它与 C 代码共享一个对象,我想使用一个结构来表示来自 C++ 库的对象.我只对对象的属性感兴趣.

The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.

我知道理想的情况是让 Example_class 环绕 C 和 C++ 代码之间的公共结构,但更改正在使用的 C++ 库并不容易.

I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.

推荐答案

C++ 标准保证一个 C struct 和一个 C++ class<的内存布局/code>(或 struct -- 同样的东西)将是相同的,前提是 C++ class/struct 符合成为 POD(普通旧数据").那么POD是什么意思?

The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean?

一个类或结构是 POD,如果:

A class or struct is POD if:

  • 所有数据成员都是公共的,它们本身是 POD 或基本类型(但不是引用或成员指针类型),或此类的数组
  • 它没有用户定义的构造函数、赋值运算符或析构函数
  • 它没有虚函数
  • 它没有基类

关于唯一允许的C++-isms"是非虚拟成员函数、静态成员和成员函数.

About the only "C++-isms" allowed are non-virtual member functions, static members and member functions.

由于您的类同时具有构造函数和析构函数,因此正式上讲不是 POD 类型,因此保证不成立.(尽管正如其他人所提到的,在实践中,只要没有虚函数,这两种布局在您尝试的任何编译器上可能是相同的.

Since your class has both a constructor and a destructor, it is formally speaking not of POD type, so the guarantee does not hold. (Although, as others have mentioned, in practice the two layouts are likely to be identical on any compiler that you try, so long as there are no virtual functions).

参见C++的[26.7]节常见问题精简版了解更多详情.

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

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