C++ 中的不可变类和内存

发布于 2024-11-07 19:30:31 字数 386 浏览 2 评论 0原文

因此,作为我正在进行的个人项目的一部分,我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗笺 2024-11-14 19:30:31

在您描述的情况下,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.

听风吹 2024-11-14 19:30:31

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文