C ++内存管理 [英] C++ Memory management

查看:135
本文介绍了C ++内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学院学到,你总是要释放你未使用的对象,但不是你实际上做什么。例如,结构化您的代码,等等。
有关于如何在C ++中处理指针的一般规则吗?

I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on. Are there any general rules on how to handle pointers in C++?

我目前不允许使用boost。我必须坚持纯c ++,因为我使用的框架禁止任何使用泛型。

I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using forbids any use of generics.

推荐答案


  1. 只有一个对象将拥有一个指针。默认情况下,这是创建者。

  2. 所有权可以传递。为了指示传递所有权,对象作为方法签名中的指针传递(例如void Foo(Bar * zonk);)。

  3. 所有者将决定何时删除对象。

  4. 要将对象传递给仅供使用的方法,该对象将作为方法签名中的引用传递(例如void Foo(Bat& zonk);)。

  5. 非所有者类只有在确定所有者在使用过程中不会破坏它们的时候,它们才可以存储对象的引用(不指针)。

  1. Only one object will ever own a pointer. By default this is the creator.
  2. Ownership can be passed on. To indicate passing of ownership, the object is passed as a pointer in the method signature (e.g. void Foo(Bar *zonk);).
  3. The owner will decide when to delete the object.
  4. To pass an object to a method just for use, the object is passed as a reference in the method signature (e.g. void Foo(Bat &zonk);).
  5. Non-owner classes may store references (never pointers) to objects they are given only when they can be certain that the owner will not destroy it during use.

基本上,如果一个类只是使用东西,它使用一个引用。如果一个类拥有一些东西,它使用一个指针。

Basically, if a class simply uses something, it uses a reference. If a class owns something, it uses a pointer.

这个工作很漂亮,是一个很高兴使用。内存问题非常罕见。

This worked beautifully and was a pleasure to use. Memory issues were very rare.

这篇关于C ++内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆