C++ 中的不可变类和内存
因此,作为我正在进行的个人项目的一部分,我对 C++ 的了解比在学校时更加深入。我是一名 Java 开发人员,因此内存管理有点难以再次适应,现在我正在不遗余力地以某种方式进行编码,我有一个关于不可变类的快速问题。
当我将它们视为一个概念时,我当然会将它们与 Java 中的字符串进行比较。但现在我使用的是 C++,重新分配操作可能会导致内存泄漏(或者至少我认为可以)。所以现在如果我这样做:
MyImmutableClass a ("blah");
a = a.modifyInSomeWay();
modifyInSomeWay 返回 MyImmutableClass 的新实例,我还没有调用解构函数。我在这里缺少什么东西会阻止“a”的第一个分配保留在内存中吗?
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.
When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:
MyImmutableClass a ("blah");
a = a.modifyInSomeWay();
where modifyInSomeWay returns a new instance of MyImmutableClass, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您描述的情况下,MyImmutableClass 的赋值运算符被调用,以将赋值的右侧复制到左侧(覆盖左侧的任何内容)手侧)。如果您的类确实是不可变的,它甚至不会有可访问的赋值运算符,并且您将收到编译错误。
如果您的对象是可变的,并且您确实有一个(正确的)赋值运算符,那么就不会出现内存泄漏,因为左侧数据的析构函数将根据需要运行以释放内存。不过,对于某些类来说,编写正确的赋值运算符可能很棘手。
Java 中不存在直接分配给(用户定义的)对象的概念,因为在那里一切都是引用。
In the case you've described, the assignment operator of
MyImmutableClass
is called to copy the right hand side of the assignment to the left hand side (overwriting whatever was on the left hand side). If your class really is immutable, it won't even have an accessible assignment operator, and you will get a compile error.If your object is mutable, and you do have a (correct) assignment operator, then there will be no memory leak because destructors for data on the left hand side will run as necessary to release memory. Writing a correct assignment operator can be tricky for some classes, though.
This concept of assigning directly to a (user-defined) object does not exist in Java, since over there everything is a reference.
Java 中很多地方都存在共享不可变值对象的风格,但由于其值语义,在 C++ 中效果不佳。说“对象应该是不可变的,但赋值仍然应该有效”是一个矛盾。您可以使用
shared_ptr
类型的变量,但这会使代码变得混乱,因此很少有人在实践中这样做。The style of sharing immutable value objects which is found in lots of places in Java does not work very well in C++ due to its value semantics. Saying "the object should be immutable, but assignment should still work" is a contradiction. You could use variables of type
shared_ptr<your_immutable_type>
, but that clutters up the code, and hence very few people do it in practice.