删除C ++中静态函数中分配的内存 [英] deleting memory allocated in static function in C++

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

问题描述

我有如下的C ++类

class anotherClass;

class myClass {
   private:
    myClass() {}
    ~myClass() {}

    typedef std::map<string, anotherClass* > stringToClass;
        static stringToClass s_stringToClass;

    public:
         static anotherClass* getStringToclass(string name);

};

在上面的类中,用于getStringToClass定义的

如下

in above class for getStringToClass defintion is as follows

anotherClass* myClass::getStringToClass(string name) {
     stringToClass::iterator iter;
     iter = s_stringToClass.find(name);

     if(iter == s_stringToClass.end()) {
          typedef stringToClass::value_type stringToClassPair;
          anotherClass* pothClass = new anotherClass();
          s_stringToClass.insert(stringToClassPair(name, pothClass));
          return pothClass;
     }
     else {
        return iter->second;
     }
}

现在我的问题是我们正在按照上面定义的静态函数分配内存.我们如何删除内存?我们可以删除析构函数中的内存,因为析构函数不是静态的吗?

now my question is we are allocating memory in static function as defined above. How can we delete memory? Can we delete memory in destructor, as destructor is not static?

感谢您的帮助.

推荐答案

如果将其存储在静态变量中,我猜您需要它们直到执行过程结束为止.如果没有,那么您需要添加一种方法,通过删除每个元素来清除此静态变量,并在不再需要它时调用它.

If you store it in a static variable, I guess you need them till the end of the execution of your process... If not, then you need to add a method to clean this static variable by deleting each element and call it when you don't need it anymore.

您不应在析构函数中执行此操作,因为静态变量未链接到您的类实例.

You should not do it in the destructor as the static variable is not linked to your class instances.

这篇关于删除C ++中静态函数中分配的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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