简体   繁体   English

C内存管理

[英]C Memory Management

The following is a sketch of how I might have some form of automated memory management in C++: 以下是我可能如何在C ++中进行某种形式的自动内存管理的示意图:

template<class T>
class Ptr{
public:
  /* Some memory management stuff (ref counting etc.)
     as Ptr object is initialized */
  Ptr( ... ) { .. }

  /* Manage reference counts etc. 
     as Ptr object is copied -- might be necessary
     when Ptr is passed to or returned from functions */
  Ptr<T>& operator=( .. ) { .. };

   /* Do memory management stuff
      when this "Pointer" object is destroyed. */
  ~Ptr() { .. }

private:
  /* Pointer to main object */
  T* object;
}

class Obj{
public:
  static Ptr<Obj> newObj( .. ) { return Ptr<Obj>( new Obj( .. ) ); }
private:
  /* Hide constructor so it can only be created by newObj */
  Obj( .. ) { .. }
  /* some variables for memory management routines */
  int refcnt;
  ..
}

This way, the end-user never has to call new or malloc, and can instead call Obj.newObj( .. ). 这样,最终用户不必调用new或malloc,而可以调用Obj.newObj(..)。

However, I'm pretty stumped on how I might do something similar for C. 但是,我很困惑如何为C做类似的事情。

It doesn't have to be exactly like above, but I don't want to have to care about memory management when it isn't important. 它不一定与上面完全相同,但是当它不重要时,我不想关心内存管理。

The biggest issue I feel I have is that when a variable in C goes out of scope, I don't really have a 'destructor' that can be signaled to let me know that the variable has gone out of scope. 我感觉到的最大问题是,当C中的变量超出范围时,我实际上并没有信号通知“析构函数”,让我知道该变量已超出范围。

Yes, that is the primary benefit of C++. 是的,这是C ++的主要优点。 You can create classes, which encapsulate functionality. 您可以创建用于封装功能的类。 And this functionality can include constructors and destructors to ensure that data is created, managed, and destroyed in a controlled manner. 并且此功能可以包括构造函数和析构函数,以确保以受控方式创建,管理和销毁数据。

There is no such option in C unless you implement an entire framework that supports such an option. 除非您实现支持该选项的整个框架,否则C中没有此类选项。

有关完整解决方案和问题的答案,请参见GObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM