简体   繁体   English

在C ++中,将数据存储在矢量对象中的效率如何?

[英]How efficient is storing data within an object in a vector in C++?

I'm making a small virtual machine; 我正在制作一个小型虚拟机; in my virtual machine I read instructions from a binary file. 在我的虚拟机中,我从二进制文件中读取指令。 Each instruction is 1 byte in size. 每条指令的大小为1个字节。 When the VM starts, it loads the binary file into a vector. VM启动时,它将二进制文件加载到向量中。 Then I use a switch and a for loop to execute the instructions. 然后,使用开关和for循环执行指令。

But here's where my question starts. 但是,这是我的问题开始的地方。 I have a vector called "Stack"; 我有一个称为“堆栈”的向量; it's my virtual machines stack for the program that's running. 这是我正在运行的程序的虚拟机堆栈。 The problem is I want to store different kinds of data in the vector (Signed and Unsigned Integers, Strings, etc ...). 问题是我想在向量中存储不同种类的数据(有符号和无符号整数,字符串等)。

To do this I created my own object (robj) and made the vector of type "robj". 为此,我创建了自己的对象(r​​obj),并创建了类型为“ robj”的向量。 This lets me store the kind of data I want, but my question is: is this wasteful? 这使我可以存储所需的数据类型,但是我的问题是:这很浪费吗?

Here's the implementation of my object: 这是我的对象的实现:

class robj {

public:
    int signed_int = 0;
    unsigned int unsigned_int = 0;

};

As you can see, my object is really small at the moment, but it will get larger as I add things like strings. 如您所见,我的对象目前确实很小,但是当我添加字符串之类的对象时,它会变得更大。 The part that I think is wasteful is that, if I store a signed integer on the stack I also have to store an unsigned one because the object defines both types of integers. 我认为浪费的部分是,如果我将有符号整数存储在堆栈中,我还必须存储无符号整数,因为该对象定义了两种类型的整数。 And this problem will only get worse as I make the object bigger. 随着我把对象变大,这个问题只会变得更糟。

So I'd just like to know, is there a less wasteful way to do this? 因此,我想知道,是否有一种不那么浪费的方法?

This is what Boost.Variant is for. 这就是Boost.Variant的目的。 It implements discriminated unions so you don't have to: 它实现了有区别的工会,因此您不必:

std::vector<boost::variant<
   int,
   unsigned int
>> v;

There can be 2 solutions 可以有2个解决方案

  1. Use union 使用联盟
union robj {
  int signed_int;
  unsigned int unsigned int;
};
  1. Use inheritance 使用继承
class type_base
{
  type_data my_type;
public:
  type_base(const type_data &t) : my_type(t) {}
  virtual parse_data() = 0;
  virtual serialize_data() = 0;
  virtual type_data get_type() {
    return my_type;
  }
  virtual type_base *clone() = 0;
};

class signed_int : public type_base {
public:
  int signed_int;
};

You can also templatize your type where the template inherits from type_base. 您还可以在模板从type_base继承的地方对类型进行模板化。

Make sure that you never make a vector of type_base which can cause object slicing. 确保永远不要创建会导致对象切片的type_base向量。 Thanks to Alain for his comment 感谢Alain的评论

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

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