在C ++中,任何处理内存分配/删除的一般准则? [英] In C++, any general guidelines for handling memory allocation/deletion?

查看:106
本文介绍了在C ++中,任何处理内存分配/删除的一般准则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能我要求的是一个网站的链接,我还没有找到。但是从Java背景来看,在C ++中处理内存分配和删除的一般准则是什么?我觉得我可能会添加各种内存泄漏到我的应用程序。我意识到有几个智能指针的变种,你也可以提及他们,但我想集中在标准的C ++指针。

Probably all that I'm asking for is a link to a website that I have yet to find. But coming from a Java background, what are the general guidelines for handling memory allocation and deletion in C++? I feel like I may be adding all sorts of memory leaks to my application. I realize that there are several variants of smart pointers, and you can mention them too me as well, but I'd like to focus on standard C++ pointers.

推荐答案

我通常的政策是这个


  • 使用智能指针, b $ b
  • 所有原始指针都由负责删除它的特定对象所拥有。

  • 构造函数总是分配指针或将其初始化为null如果要设置

  • 这些规则确保指针在删除自己的对象时被删除,从而消除最常见的内存泄漏情况。

  • 不要将内部指针传递给另一个对象,始终传递容器对象,并调用函数调用成员函数对容器对象执行指针。

  • 禁用复制容器对象。在极少数情况下,实现副本,以便它将指向的对象复制。但不允许复制拥有对象,而不复制包含的对象。

  • 前两个规则确保您不能拥有指向已删除内存的指针副本。

  • 不要尝试实施引用计数。如果你需要一个引用计数指针,使用智能指针类并包含它。

  • Use smart pointers where usage is at all complex.
  • All raw pointers are owned by a specific object that is responsible for deleting it.
  • The constructor always either allocates the pointer or initializes it to null if it's to be set later.
  • The destructor always deletes any contained pointers
  • Those rules ensure that pointers get deleted when their owning objects are deleted eliminating most common memory leak situations.
  • Never pass an internal pointer into another object, always pass the container object and have the the called function call member functions of the container object to act on the "pointer".
  • Disable copying of the container object. In rare cases implement the copy so that it copies the pointed to object. But never allow the owning object to be copied without also copying the contained object.
  • The previous two rules ensure that you can't have copies of the pointer pointing to deleted memory.
  • Don't try to implement reference counting. If you need a reference counted pointer use a smart pointer class and contain that.

我发现这些规则通常可以使用原始指针安全高效地,如果你想打破这些规则,然后使用智能指针。

I've found those rules generally ensure you can use raw pointers safely and efficiently, and if you want to break those rules then use a smart pointer instead.

这篇关于在C ++中,任何处理内存分配/删除的一般准则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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