c++ - 在 C++ 中创建不可变且高效的类的惯用方法
问题描述
我想做这样的事情(C#)。
public final class ImmutableClass {
public readonly int i;
public readonly OtherImmutableClass o;
public readonly ReadOnlyCollection<OtherImmutableClass> r;
public ImmutableClass(int i, OtherImmutableClass o,
ReadOnlyCollection<OtherImmutableClass> r) : i(i), o(o), r(r) {}
}
我遇到的潜在解决方案及其相关问题是:
1.const
用于类成员,但这意味着删除了默认的复制赋值运算符。
解决方案1:
struct OtherImmutableObject {
const int i1;
const int i2;
OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {}
}
问题1:
OtherImmutableObject o1(1,2);
OtherImmutableObject o2(2,3);
o1 = o2; // error: use of deleted function 'OtherImmutableObject& OtherImmutableObject::operator=(const OtherImmutableObject&)`
编辑:这很重要,因为我想将不可变对象存储在 astd::vector
但接收error: use of deleted function 'OtherImmutableObject& OtherImmutableObject::operator=(OtherImmutableObject&&)
2.使用get方法和返回值,但这意味着必须复制大对象,这是我想知道如何避免的低效率。该线程建议了 get 解决方案,但它没有解决如何在不复制原始对象的情况下处理传递的非原始对象。
解决方案2:
class OtherImmutableObject {
int i1;
int i2;
public:
OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {}
int GetI1() { return i1; }
int GetI2() { return i2; }
}
class ImmutableObject {
int i1;
OtherImmutableObject o;
std::vector<OtherImmutableObject> v;
public:
ImmutableObject(int i1, OtherImmutableObject o,
std::vector<OtherImmutableObject> v) : i1(i1), o(o), v(v) {}
int GetI1() { return i1; }
OtherImmutableObject GetO() { return o; } // Copies a value that should be immutable and therefore able to be safely used elsewhere.
std::vector<OtherImmutableObject> GetV() { return v; } // Copies the vector.
}
问题2:不必要的副本效率低下。
3. 使用 get 方法并返回const
引用或const
指针,但这可能会留下挂起的引用或指针。该线程讨论了引用超出函数返回范围的危险。
解决方案3:
class OtherImmutableObject {
int i1;
int i2;
public:
OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {}
int GetI1() { return i1; }
int GetI2() { return i2; }
}
class ImmutableObject {
int i1;
OtherImmutableObject o;
std::vector<OtherImmutableObject> v;
public:
ImmutableObject(int i1, OtherImmutableObject o,
std::vector<OtherImmutableObject> v) : i1(i1), o(o), v(v) {}
int GetI1() { return i1; }
const OtherImmutableObject& GetO() { return o; }
const std::vector<OtherImmutableObject>& GetV() { return v; }
}
问题3:
ImmutableObject immutable_object(1,o,v);
// elsewhere in code...
OtherImmutableObject& other_immutable_object = immutable_object.GetO();
// Somewhere else immutable_object goes out of scope, but not other_immutable_object
// ...and then...
other_immutable_object.GetI1();
// The previous line is undefined behaviour as immutable_object.o will have been deleted with immutable_object going out of scope
由于从任何方法返回引用,可能会发生未定义的行为Get
。
解决方案
您确实想要某种类型的不可变对象加上值语义(因为您关心运行时性能并希望避免堆)。只需
struct
用所有数据成员定义一个public
。struct Immutable { const std::string str; const int i; };
您可以实例化和复制它们,读取数据成员,但仅此而已。从另一个的右值引用移动构造一个实例仍然复制。
Immutable obj1{"...", 42}; Immutable obj2 = obj1; Immutable obj3 = std::move(obj1); // Copies, too obj3 = obj2; // Error, cannot assign
这样,您确实可以确保您的类的每次使用都尊重不变性(假设没有人做坏事
const_cast
)。可以通过自由函数提供附加功能,将成员函数添加到数据成员的只读聚合是没有意义的。您想要 1.,仍然具有值语义,但稍微放松(这样对象不再是真正不可变的)并且您还担心为了运行时性能而需要移动构造。没有办法绕过
private
数据成员和 getter 成员函数:class Immutable { public: Immutable(std::string str, int i) : str{std::move(str)}, i{i} {} const std::string& getStr() const { return str; } int getI() const { return i; } private: std::string str; int i; };
用法是相同的,但移动构造确实移动。
Immutable obj1{"...", 42}; Immutable obj2 = obj1; Immutable obj3 = std::move(obj1); // Ok, does move-construct members
现在是否允许分配由您控制。
= delete
如果您不想要它,只需使用赋值运算符,否则使用编译器生成的运算符或实现您自己的运算符。obj3 = obj2; // Ok if not manually disabled
您不关心值语义和/或原子引用计数增量在您的场景中是可以的。使用@NathanOliver 的答案中描述的解决方案。
推荐阅读
- javascript - 仅当屏幕尺寸足够大时才显示背景图像
- c# - MassTransit Azure 服务总线请求-响应 ASP.NET Core RequestTimeoutException
- reactjs - 如何在 React js 中创建 3 个(国家、州和城市)下拉菜单以相互填充数据
- python-3.x - 使用 sqlalchemy 和烧瓶迁移的 Postgresql 分区管理
- python - 长寿命 Websocket 连接
- audio - 在 ffmpeg 中混合音轨的文件上添加另一个音频
- c++ - 在 C++ 中使用 opencv waitkey()
- javascript - 使用鼠标悬停事件更改 JavaScript 中元素的颜色
- asp.net-mvc - 创建新记录时的自定义验证
- javascript - 以前的子节点事件处理程序未触发