這是我無法理解。 比方說,我重載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