【问题标题】:scoped_ptr for double pointersscoped_ptr 用于双指针
【发布时间】:2014-07-16 11:31:26
【问题描述】:

有没有一种优雅的方式来升级到使用 boost 的 scoped_ptr 或 scoped_array 截断的以下代码?

MyClass** dataPtr = NULL;
dataPtr = new MyClass*[num];
memset(dataPtr, 0, sizeof(MyClass*));
allocateData(dataPtr); // allocates objects under all the pointers

// have fun with the data objects

// now I'm bored and want to get rid of them
for(uint i = 0; i < num; ++i)
  delete dataPtr[i];
delete[] dataPtr;

【问题讨论】:

  • 可以修改 allocateData() 吗?
  • 理论上我可以,但是由于很多旧代码都以这种方式使用这个函数,所以我很犹豫是否这样做,并且更喜欢一个不修改它的解决方案。

标签: boost double-pointer scoped-ptr


【解决方案1】:

我现在是这样做的:

boost::scoped_array<MyClass*> dataPtr(new MyClass*[num]);
memset(dataPtr.get(), 0, num * sizeof(MyClass*));
allocateData(dataPtr.get());

似乎工作正常。

【讨论】:

  • 您仍然需要手动释放数组中的所有元素。
  • 是的,我刚刚使用 Visual Leak Detector 识别出内部指针不会被删除。我想我必须嵌套 scoped_ptrs 才能这样做。我想我会继续手动删除。
  • 只需重写allocateData。该功能是糟糕设计的完美案例。
猜你喜欢
  • 1970-01-01
  • 2014-05-13
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2023-03-14
相关资源
最近更新 更多