【发布时间】:2012-12-11 02:19:22
【问题描述】:
Richard Gillam 在他的"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=() throws,bar1 和bar2 会泄漏。
【问题讨论】:
-
哇
try-catch,这一定是编写异常安全代码的最糟糕方式... -
在文章后面作者提供了一个使用 auto_ptr 的解决方案,我认为这是正确的。
-
auto_ptrs?那些已经被弃用的? -
我认为 unique_ptr 当时不可用
-
我想到了复制交换。不过@user1042389、
boost::shared_ptr可能是。
标签: c++ memory-leaks assignment-operator