什么时候可以安全地使用来自其他类的char数组?

时间:2018-12-26 10:13:47

标签: c++

我有两个类,B类包含一个静态函数“ funcEx”,该函数具有一个指针作为参数。 funcEx应该将参数数据插入到地图中。

A类使用此funx以便将参数保留在静态映射内。 A类被摧毁后会发生什么。 会释放“ param_name”的内存分配吗?

class A{
B::funcEx("param_name");
}

class B{
static map<const char*, int, cmp_str> *Map1 ;
static Map1 = new std::map<const char *, int, cmp_str>();

static funcEx(const char * param){
Map1.insert(param,8)
}

}

1 个答案:

答案 0 :(得分:1)

据说,像“ param_name”这样的文字字符串是不朽的。

尝试回答您:

#include <map>

class B {
  public:
    static void funcEx(const char * param) {
      map[param] = 8;
    }
  private:
    static std::map<const char *, int> map;
};

std::map<const char *, int> B::map;

class A {
  public:
    A(char c) { member[0] = c; member[1] = 0; }
    void f() { B::funcEx("param_name"); }
    void g() { B::funcEx(member); }
    void h(char * s) { B::funcEx(s); }
  private:
    char member[2];
};

int main(int, char **)
{
   A * x = new A('x');
   {
     A y('y');

     {
       char s[] = "ab";

       x->f(); // nothing change with y->f()
       x->g();
       y.g();
       x->h(s); // x can be y

       // here all the keys/pointers into the map still exist

       delete x;

       // here x is deleted
       // => x->member has an unknown value
       // => "x" used as a key in the map is an invalid pointer, may be it is not anymore the string "x"
     }

     // here 's' does not exist anymore
     // the key "ab" in the map is an invalid pointer, may it is not anymore the string "ab"
   }

   // here 'y' does not exist
   // => y.member has an unknown value
   // => "y" used as a key in the map is an invalid pointer, may be it is not anymore the string "y"

   return 0;
}

因为B中的所有内容都是静态的,所以该类没有真正的兴趣