列表中的原始指针与唯一指针
Raw vs Unique pointers in the list
假设我有一个类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++自动管理列表的资源,这在列表在本地作用域中声明的情况下尤其重要,因为您不必担心过早退出作用域。
相关文章:
- 何时在引用或唯一指针上使用移动语义
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 如何更改唯一指针向量的可见性
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- C++尝试深度复制唯一指针时出现内存访问冲突
- 使用 RTTI 克隆唯一指针的向量
- 为什么我无法创建唯一指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- 将唯一指针的指针传递给采用双指针的函数
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- C++唯一指针的向量
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 指向基类的唯一指针
- 添加要映射的对象的唯一指针
- 智能指针(唯一指针)和引用
- 唯一指针是否在堆或堆栈上分配内存?
- 尝试设置唯一指针布尔数组的值时BAD_ACCESS错误
- 使用唯一指针调用函数会使我的程序崩溃
- 智能指针(唯一指针)总是比普通指针更可取