习惯的方式来声明C ++不可变类 [英] Idiomatic Way to declare C++ Immutable Classes
问题描述
所以我有一些相当广泛的功能代码,其中主要的数据类型是不可变的structs /类。我一直声明不变性的方式是几乎不可变的通过成员变量和任何方法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.
所以一个替代方法是重写你的struct作为一个私有数据成员的类,只有public const函数。
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对象是(pseudo-)不可变的,您仍然可以进行分配。
In this way, your RockSolid objects are (pseudo-)immutables, but you are still able to make assignments.
这篇关于习惯的方式来声明C ++不可变类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!