TCPL 问题2: 如下代码有什么风险?
阅读TCPL 第4版时,遇到一个看不明白的话
class Shape{......};
Shape* read_shape(int nStyle)
{
return new shape(...);
}
void user()
{
std::vector<Shape*>v;
while (...)
v.push_back(read_shape(...));
//....
for (auto p : v) delete p; // remember to delete elements
}
TCPL上说有两个风险
1、 A user might fail to delete the pointer returned by read_shape();
我理解是,在 v.pushback出错之后, 用户将不能删除ReadShape的堆内存
2、 The owner of a container of Shape pointers might not delete the objects pointed to.
我翻译这句话是:保存指向shape指针的容器 v不能删除指针指向的对象。 这怎么可能呢? 既然已经在我容器里面了,我怎么可能释放不了内存呢?
然后,书上接着说 std::unique_ptr 能解决问题。 unique_ptr 能解决问题2?