理查德·吉勒姆在他"The Anatomy of the Assignment Operator"可能作出錯誤陳述時,他說了這樣,就在他的論文開始:我的錯誤信息是否正確?
「一個正確的答案,這個問題會是這個樣子:」
TFoo&TFoo::operator=(const TFoo& that)
{
if (this != &that)
{
TBar* bar1 = 0;
TBar* bar2 = 0;
try
{
bar1 = new TBar(*that.fBar1);
bar2 = new TBar(*that.fBar2);
}
catch (...)
{
delete bar1;
delete bar2;
throw;
}
TSuperFoo::operator=(that);
delete fBar1;
fBar1 = bar1;
delete fBar2;
fBar2 = bar2;
}
return *this;
}
我認爲作者是錯誤的,因爲如果TSuperFoo::operator=()
拋出,bar1
和bar2
會泄漏。
Wow'try-catch',這必須是寫作_exception safe_ code的_worst_方式... –
本文後面的作者提供了一個使用auto_ptr的解決方案,我認爲這是正確的。 – Belloc
'auto_ptr's?那些已被棄用? –