在 C++ 中实现默认值
我有一个包含一组属性的类,我希望能够从另一个实例(名为父级)获取默认值。
如果实例没有父实例,则会为其分配默认值。 但是,如果实例有父级,那么我希望它将其属性默认为父级的属性,但有限制:如果父级属性被修改,则对象属性也可以获得新值。 鉴于此限制,我不能简单地从父级复制值。
因此我认为我有两种方法:
- 使用指针:如果指针为 nullptr,则使用父值。
- 对每个属性使用布尔字段,指示状态。
这两种方法都应该有效,但它们也有不方便的地方:
- 第一种方法需要手动实例化,即使它可以使用shared_ptr或unique_ptr来简化。但这会导致额外的指令,从而使代码变慢
- 第二个会导致额外的内存消耗:每个实例每个属性至少多占用一个字节(大多数情况下是2、4甚至8个字节)。
我的问题是:还有其他方法可以实现这种行为吗?或者什么是最好的解决方案?
I have a class containing a set of attributes, which I want to be able to have default values get from another instance (named parent).
If the instance does not have a parent, then it is assigned default values.
But if the instance have a parent, then I would like it to default its attributes to the parent's ones, with the restriction that if the parent attributes are modified then the object attributes can also get the new value.
Given this restriction, I can't simply copy the values from the parent.
Thus I think I have two methods:
- Use pointers: if the pointer is nullptr then use the parent value.
- Use a bool field for each attribute, indicating the status.
Both methods should work, but they also have incovenient:
- The first will need manual instantiation even if it can be simplified with shared_ptr or unique_ptr. But this will lead to additional instructions, thus slower code
- The second will lead to additional memory consumption : each instance will take at least one more byte (most of time 2, 4 or even 8 bytes) per attribute.
My question is: Is there any other way to implement such behavior? Or what is the best solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
然后使用位域或位掩码为每个属性使用一个位。没有什么比这更有效的了。
Then use a bitfield or bit mask to use one single bit for each attribute. Nothing more efficient than that.
也许可以使用以下基本构建块: 可默认引用:
现在您可以使用现有引用初始化此类对象,或者将其留空,它将构造一个您有引用的新对象。
Maybe the following basic building block can be used: A defaultable reference:
Now you can initialize such an object either with an existing reference, or leave it blank and it'll construct a new object to which you have a reference.