C++在STL容器中使用智能指针

use*_*935 0 c++ stl smart-pointers

知道这些容器已经管理了内存,在STL容器(向量,地图等)中使用智能指针有什么好处?

例:

std::vector<std::unique_ptr<int>>
Run Code Online (Sandbox Code Playgroud)

代替

std::vector<int*>
Run Code Online (Sandbox Code Playgroud)

nwp*_*nwp 5

如果对象是指针,则管理指针所占用的内存是不够的.您还需要管理指针指向的内容.最好存储指向的对象而不是指针(如果你的例子std::vector<int>是合适的话),但是,如果你有不可能的多态对象.