这是我无法理解。 比方说,我重载operator &制造和和两个对象,和运营商之间=进行分配(使对象的副本)。 让我们假设我有一个命名为A类,而这个代码:运营商超载:内存泄漏
A a1,a2,a3;
// initialize a1,a2,a3
a1=a2&a3;
如果A1已经分配的,当我A1分配对a2 & A3,有内存泄漏? 是在不删除旧对象的情况下创建的新对象?
PS:运营商使用A型的两个参数,重载(我还没有定义的类A,这是一个例子),返回类型A的参数,被定义为类的朋友。
代码:
这是一个很长的代码,所以我用引擎收录: http://pastebin.com/42TnThfC 但因为它是很长,我也张贴了最有意义的部分:
template<class T>
List<T>& List<T>::operator= (List<T>& l)
{
List<T>* ptr=l.next;
if(this!=&l)
{
resize(0);
while(!ptr->end)
{
push(ptr->info);
ptr=ptr->next;
}
}
return *this;
}
template <class T>
List<T>& operator& (List<T>& l1, List<T>& l2) throw()
{
List<T>* temp,*ptr=l1.next;
temp=new List<T>();
try
{
if((l1.end)^(l2.end))
throw excp1;
}
catch (char *s)
{
cout << "Exception: "<<s<<endl;
}
if(l1.end)
{
while(!ptr->end)
{
if(l2.in(ptr->info))
temp->push(ptr->info);
ptr=ptr->next;
}
}
else
{
if(l1.info==l2.info)
temp->push(l1.info);
}
return *temp;
}
这是一个列表,推推动的物品,主要的例子:
int main(int arcg, char **argv)
{
List<T>l1,l2,l3;
for(int i=0;i<10;i++)
{
l1.push(i);
l2.push(i);
l3.push(i);
}
l3=l1&l2;
}
这种情况L3已经L1 & L2,但无线这会导致内存泄漏?
我们需要更多的代码。像赋值运算符和&运算符一样能够帮助您。 – 2012-01-29 17:57:32