std::map<struct, int> 我需要析构函数吗?
std::map<struct, int> Do I need destructor ?
嗨,在 cpp class X 我有一个
class X{
private:
std::map<some_struct, int> C;
}
其中 some_struct 定义为:
typedef struct{
int a;
int b;
int c;
}some_struct;
我的问题是:我需要在 X 的析构函数中指定关于映射 C 的任何内容吗?
如果是,X 的析构函数应该对映射 C 执行什么操作?
不,您不需要为 some_struct
或 class X
指定析构函数
对于任何类型,它都是由编译器自动生成的。只要在使用 new
或 new []
的动态存储中没有使用 class 显式分配任何内容,您就不需要编写应用 delete
或delete[]
操作。
另外,对于编写 C++ 代码(与 C 相比),您不需要使用 typedef
语法:
struct some_struct {
int a;
int b;
int c;
};
只要不引入 new
运算符,就可以使用默认析构函数。
ALL STL 容器(映射、向量、列表、双端队列等...)不需要特殊的析构函数。它们是独立的,设计简洁,一旦你超出范围就会自我毁灭。
如果您使用 new
运算符在堆上动态分配对象,则需要担心析构函数中的 C
,例如:
class X{
public:
X();
private:
std::map<some_struct, int> *p_C;
}
在定义中:
X::X() {
p_C = new map<some_struct, int>();
}
X::~X() {
if(p_C) delete p_C;
}
嗨,在 cpp class X 我有一个
class X{
private:
std::map<some_struct, int> C;
}
其中 some_struct 定义为:
typedef struct{
int a;
int b;
int c;
}some_struct;
我的问题是:我需要在 X 的析构函数中指定关于映射 C 的任何内容吗? 如果是,X 的析构函数应该对映射 C 执行什么操作?
不,您不需要为 some_struct
或 class X
对于任何类型,它都是由编译器自动生成的。只要在使用 new
或 new []
的动态存储中没有使用 class 显式分配任何内容,您就不需要编写应用 delete
或delete[]
操作。
另外,对于编写 C++ 代码(与 C 相比),您不需要使用 typedef
语法:
struct some_struct {
int a;
int b;
int c;
};
只要不引入 new
运算符,就可以使用默认析构函数。
ALL STL 容器(映射、向量、列表、双端队列等...)不需要特殊的析构函数。它们是独立的,设计简洁,一旦你超出范围就会自我毁灭。
如果您使用 new
运算符在堆上动态分配对象,则需要担心析构函数中的 C
,例如:
class X{
public:
X();
private:
std::map<some_struct, int> *p_C;
}
在定义中:
X::X() {
p_C = new map<some_struct, int>();
}
X::~X() {
if(p_C) delete p_C;
}