列表中的原始指针与唯一指针

Raw vs Unique pointers in the list

本文关键字:指针 唯一 原始 列表      更新时间:2023-10-16

假设我有一个类T.的std::列表

管理这些元素的最佳方式是什么?考虑到只有经理(我的意思是——唯一的所有者)可以添加或删除列表中的项目。

1)

std::list < T* > myList;
//adding the new element
myList.push_back( new T(..) );
//deleting the one element
...roaming through the list...got it...
delete *iterator;
myList.erase(iterator);

2)

std::list < std::unique_ptr<T> > myList;
//adding the new element
myList.push_back ( std::unique_ptr<T>( new T(..) );
//deleting the one element
...roaming through the list...got it...
myList.erase(iterator);

用Herb Sutter的GotW列的话来说:

指导原则:要分配对象,更喜欢通过编写make_unique默认情况下,并在知道对象的生存期为时写入make_shared将使用shared_ptrs进行管理。

std::list < std::unique_ptr<T> > myList;
//adding the new element
myList.push_back ( std::make_unique<T>(..) );
//deleting the one element
...roaming through the list...got it...
myList.erase(iterator);

对于std::make_unique实现,您可以使用StephanT.Lavavej接受的C+14建议。

如果程序中的所有权模型是列表"拥有"其中的元素,则第二种方式(即使用unique_ptr<T>)更好。它允许C++自动管理列表的资源,这在列表在本地作用域中声明的情况下尤其重要,因为您不必担心过早退出作用域。