我读到 assign 方法会在向其分配任何内容之前清除 vector 目标索引。这是否意味着如果我们有一个 vector ,例如:
vector<foo*> somevector;
然后 assign 方法实际上会在将数据复制到目标索引之前删除 foo*。
最佳答案
then the assign method would actually delete foo* before copying data to the target indexes.
不会,它只会删除指针本身但不会删除指针指向的对象。
在STL 容器中使用原始指针时需要小心。如果您在 somevector
中动态分配元素,您最终会泄漏内存。
更多的实践方法是在STL容器中使用智能指针,动态分配的内存将在以下情况下被释放:
std::vector<std::unique_ptr<foo>> somevector;
关于c++ - vector 插入和分配之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193087/