【发布时间】:2010-10-15 03:55:40
【问题描述】:
typedef struct temp
{
int a,b;
char *c;
temp(){ c = (char*)malloc(10);};
~temp(){free(c);};
}temp;
int main()
{
temp a;
list<temp> l1;
l1.push_back(a);
l1.clear();
return 0;
}
给出分段错误。
【问题讨论】:
-
除非您有充分的理由不这样做,否则您应该尝试养成使用 new & delete 而不是 malloc & free 的习惯。
-
你不需要在 C++ 中“typedef”结构,只需要在 C 中。
-
重要提示:当你定义任何类或结构时,尤其是指针成员,声明 operator= 和复制构造函数为私有的。 “私有:temp& operator=(const temp&); temp(const temp&);”如果你对需要复制的类做任何事情,它不会编译,你知道你必须提供它们。
-
... 要么写一个做正确的事,在这种情况下,或者只是删除声明并获取默认副本,如果这些对有问题的类有用。跨度>
标签: c++ memory memory-management stl pointers