inf*_*ler 6 c++ smart-pointers c++11
我正在使用一个旧的开源库,其中包含以下(简化)API:
// some class that holds a raw pointer to memory on the heap
// DOES NOT delete it in its destructor
// DOES NOT do a "deep" copy when copied/assigned (i.e., after copying both objects
// will point to the same address)
class Point;
// function used to construct a point and allocate its data on the heap
Point AllocPoint();
// function used to release the memory of the point's data
void DeallocPoint(Point& p);
// Receives a pointer/c-array of Points, along with the number of points
// Doesn't own the memory
void Foo(Point* points, int npts);
Run Code Online (Sandbox Code Playgroud)
在C++ 11中使用此API的最佳方式(最安全/最可读/最优雅)是什么.我不能简单地使用vector<unique_ptr<Point, PointDeleter>>(PointDeleter我可以实现一个简单的自定义删除器),因为那时我将无法使用该函数Foo(期望Point*与否unique_ptr<Point>*).
谢谢
“你”可以编写一个简单的包装器来释放内存:
struct PointVectorWrapper {
vector<Point> points;
~PointVectorWrapper() {
for (Point& p : points) {
DeallocPoint(p);
}
}
PointVectorWrapper& operator=(const PointVectorWrapper&) = delete;
PointVectorWrapper(const PointVectorWrapper&) = delete;
};
// Now the usage is simple and safe:
PointVectorWrapper points;
// ... populate points ...
Foo(points.data(), points.size())
Run Code Online (Sandbox Code Playgroud)
但这似乎有点“临时”。什么是更标准/可重用的解决方案?
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |