Idiomatic Way to declare C++ Immutable Classes(声明 C++ 不可变类的惯用方法)
问题描述
所以我有一些非常广泛的功能代码,其中主要数据类型是不可变的结构/类.通过将成员变量和任何方法设为 const,我一直在声明不变性的方式是实际上不可变的".
So I have some pretty extensive functional code where the main data type is immutable structs/classes. The way I have been declaring immutability is "practically immutable" by making member variables and any methods const.
struct RockSolid {
const float x;
const float y;
float MakeHarderConcrete() const { return x + y; }
}
这真的是 C++ 中我们应该这样做"的方式吗?或者有更好的方法吗?
Is this actually the way "we should do it" in C++? Or is there a better way?
推荐答案
你提出的方法完全没问题,除非在你的代码中你需要对 RockSolid 变量进行赋值,就像这样:
The way you proposed is perfectly fine, except if in your code you need to make assignment of RockSolid variables, like this:
RockSolid a(0,1);
RockSolid b(0,1);
a = b;
这将不起作用,因为编译器会删除复制赋值运算符.
This would not work as the copy assignment operator would have been deleted by the compiler.
因此,另一种方法是将结构重写为具有私有数据成员且仅具有公共常量函数的类.
So an alternative is to rewrite your struct as a class with private data members, and only public const functions.
class RockSolid {
private:
float x;
float y;
public:
RockSolid(float _x, float _y) : x(_x), y(_y) {
}
float MakeHarderConcrete() const { return x + y; }
float getX() const { return x; }
float getY() const { return y; }
}
这样,您的 RockSolid 对象是(伪)不可变的,但您仍然可以进行赋值.
In this way, your RockSolid objects are (pseudo-)immutables, but you are still able to make assignments.
这篇关于声明 C++ 不可变类的惯用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声明 C++ 不可变类的惯用方法


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01