C++ 何时可以安全地使用来自不同类的字符数组?
我有两个类,B类包含一个静态函数funcEx,它的指针是param。funcEx应将参数数据插入到映射中 类A使用这个funx将参数保存在静态映射中。 A级被摧毁后会发生什么。 参数名称的内存分配是否会被释放C++ 何时可以安全地使用来自不同类的字符数组?,c++,C++,我有两个类,B类包含一个静态函数funcEx,它的指针是param。funcEx应将参数数据插入到映射中 类A使用这个funx将参数保存在静态映射中。 A级被摧毁后会发生什么。 参数名称的内存分配是否会被释放 class A{ B::funcEx("param_name"); } class B{ static map<const char*, int, cmp_str> *Map1 ; static Map1 = new std::map<const char *, int
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)
}
}
正如所说,像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中的所有内容都是静态的,所以该类没有真正的兴趣这不是C++您是否介意给我们一个更完整的示例(理想情况下是a)。我们需要知道字符串文字在类A等中的确切存储方式,才能给出正确答案。在您的示例中,param_name是字符串文字,它将一直存在到程序结束,因此指向它的指针可以安全地保存在映射中。这是你的问题吗?如果是,您的伪代码就没有意义了,因为func是类B的一部分,但在A中调用。您的示例仍然没有多大意义。如果要在A中调用funcEx,则必须使用限定名称进行查找,例如B::funcEx。此外,字符串文本不能作为char*传递,只能作为const char*。还要注意,我前面的注释仅适用于字符串文字,而不适用于字符数组。此外,还缺少映射声明、访问说明符和中调用的封闭函数。如果您使用std::string而不是const char,则类应该是classic。该类将自动复制字符串文本,您不再需要担心原始字符串的生存期。