如果我有以下课程:
// ComponentMan.h
class ComponentMan
{
public:
template<class T>
void CreateComponent<T>()
{
T* temp = new T();
delete temp; // Memory leak?
}
}
- 删除 temp 会导致内存泄漏吗?
- 因为程序不知道 T 的大小?
- 如果是这样,我该如何避免它?
如果我有以下课程:
// ComponentMan.h
class ComponentMan
{
public:
template<class T>
void CreateComponent<T>()
{
T* temp = new T();
delete temp; // Memory leak?
}
}
这里没有内存泄漏,因为程序知道. temp
编译器在编译时用实际类型替换模板化参数,因此当程序运行时它完全知道temp
在删除时,编译器不知道 指向的对象的大小temp
,但它不需要知道,因此没有泄漏。例如:
struct T { int t; };
struct U : public T { int u; };
T * temp = new U();
delete temp; // compiler doesn't know whether it's dealing with a T or a U
暂时忘掉 C++,只考虑 C。
int * ptr = malloc(100);
free(ptr);
即使我们不必提醒编译器我们的 int 数组有多大,这个 C 代码也可以工作。
(Edit: To clarify that we're talking about deletion-time here. The compiler knows more at creation time than at deletion time. The question is "how does the system know, at deletion time, how much memory to delete?". One answer is at http://c-faq.com/malloc/freesize.html)