Here's how I would write that:
std::vector<std::unique_ptr<p2t::Point>> polyline;
for (const CCPoint& p : points)
polyline.push_back(std::unique_ptr<p2t::Point>(new p2t::Point(p.x, p.y)));
Note use of a reference saves doing the lookup twice, but without copying the point. unique_ptr
ensures the memory is later freed correctly with delete
, you no longer need to do that yourself. And the range-based for creates shorter more readable code, and also avoids the redundant range-checking inside at()
.
In C++14 it gets even more efficient:
std::vector<std::unique_ptr<p2t::Point>> polyline;
for (const CCPoint& p : points)
polyline.emplace_back(std::make_unique<p2t::Point>(p.x, p.y));
Note that storing points by pointer is not ideal from a performance perspective. That's something you usually do when you want a polymorphic collection. Does p2t::Point
have virtual member functions?