[英]Ways of deleting pointers in a vector [C++ ]
std::vector<Circle*> circles
for(int i=0; i<circles.size(); i++) // 1
delete circles[i];
for(auto & circle : circles) // 2
delete circle;
for(Circle * circle : circles) // 3
delete circle;
for(Circle *& circle : circles){ // 4
delete circle;
If I write it the first way, CLion IDE suggests me to use the second way so I guess they're the same.如果我用第一种方式写,CLion IDE 建议我使用第二种方式,所以我猜它们是一样的。 I'm not really sure why there's a reference next to auto and if any of methods 3 or 4 are correct as well?我不太确定为什么 auto 旁边有一个引用,以及方法 3 或 4 中的任何一个是否也正确? I would guess 4 is also same as 1 and 2.我猜 4 也与 1 和 2 相同。
For completeness, there's one more way:为了完整起见,还有另一种方法:
for(auto circle : circles)
delete circle;
Now, all these ways in this example are equivalent and will do the job of deleting circles
elements equally well.现在,此示例中的所有这些方式都是等效的,并且同样可以很好地完成删除circles
元素的工作。
Having a reference to a pointer doesn't matter (the reference is "unwrapped" in expressions - in technical terms an lvalue-to-rvalue conversion), in all cases the actual pointer value is passed to delete
.对指针的引用无关紧要(引用在表达式中“展开” - 用技术术语来说是左值到右值的转换),在所有情况下,实际的指针值都会传递给delete
。
The IDE seems to be suggesting the most idiomatic way of writing a range-based for loop: IDE 似乎暗示了编写基于范围的 for 循环的最惯用方式:
for(auto & elem : collection)
This is usually the safest form;这通常是最安全的形式; this way if collection
contains large objects, they will be iterated by reference, without unnecessary copying.这样,如果collection
包含大对象,它们将通过引用进行迭代,而无需不必要的复制。 It doesn't matter in our case as a trivial type like a pointer can be easily copied.在我们的例子中这并不重要,因为像指针这样的普通类型可以很容易地复制。
PS As others have noted, in modern C++ we try to avoid new
and delete
and use value semantics and smart pointers instead. PS 正如其他人所指出的,在现代 C++ 中,我们尝试避免使用new
和delete
,而是使用值语义和智能指针。 So something simple like std::vector<Circle> circles
could be all that's needed, or if pointers are required, std::vector<std::unique_ptr<Circle>> circles
.所以像std::vector<Circle> circles
这样简单的东西可能就是所需要的,或者如果需要指针, std::vector<std::unique_ptr<Circle>> circles
。 No manual cleanup necessary in both cases.在这两种情况下都不需要手动清理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.