C ++将属性转换为指针以减少类的大小是否有缺点? [英] C++ Are there disadvantages in turning attributes into pointers to reduce size of class?

查看:79
本文介绍了C ++将属性转换为指针以减少类的大小是否有缺点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在课堂上使用std::vector<T>(16个字节).这使我的班级的大小增加了16个字节.蜜蜂繁重的使用类(也在数组中),我考虑用std::unique_ptr<std::vector<T>>替换std::vector<T>以减小到4个字节的大小.那么这样做有什么不利之处吗?还是这只是设计内存友好类的通常步骤?

I am using a std::vector<T> (16 bytes) in my class. This increases the size of my class by 16 bytes. Beeing a heavy used class (also in arrays), I considered replacing std::vector<T> with std::unique_ptr<std::vector<T>> to go down to 4 bytes of size. So are there any disadvantages in doing so? Or is this just a usual step in designing memory friendly classes?

我首先考虑这种方法,因为我假设我的类实例中没有构造任何指针.但是,很显然,正如SergeyA指出的那样,std::optional在这里是一个更好的选择.

I was considering this method in the first place, because I assumed instances of my class where I don't construct any of my pointers. But appearently std::optional is a better choice here, as SergeyA thankfully pointed out.

由于答案是是,所以有缺点,并且std::optional也不是我想要的,我想我需要进一步澄清(并解释更多我的实现).我将在另一篇文章中重写我的问题.事实证明,这比我最初预期的要复杂得多.

Edit 2: Since the answer is Yes, there are disadvantages and std::optional isn't exactly what I was looking for either, I feel like I have to clarify further (and explain more of my implementation). I will re-write my question in another post. This turns out to be a lot more complicated than I initially expected.

推荐答案

这样做,您将增加应用程序的内存消耗-现在每个对象将为unique_ptr使用8个字节除了向量的16个字节外,还分配给动态存储(堆)中的其他位置.

By doing so, you would increase the memory consumption of the application - now every object will use 8 bytes for the unique_ptr in addition to 16 bytes for the vector, allocated somewhere else in the dynamic storage (heap).

访问该向量时,您还会增加内存碎片并增加一个额外的间接步骤-导致性能下降.

You also would increase memory fragmentation and add an extra indirection step when accessing the said vector - resulting in performance degradation.

但是,如果您具有可选性,即某些对象将具有矢量,但有些对象将不具有矢量,则最好使用专门设计的工具来表达它:std::optional(C ++ 17或在C ++ 17之前的编译器中).

However, if you have optionality, that is, some objects would have vector, but some would not, it would be better to express this with a specifically designed tool: std::optional (part of C++17 or experimental in pre-C++17 compilers).

这篇关于C ++将属性转换为指针以减少类的大小是否有缺点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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