用于动态填充对象并在返回时销毁的c++习语

C++ idiom for dynamically populating objects and destroying at return

本文关键字:c++ 习语 返回 填充 动态 对象 用于      更新时间:2023-10-16

我用的是c++ 0x。

我有一个函数call_third_party,它接收A*的列表,将其转换为B*的列表,然后将B*的列表传递给函数third_party。调用third_party后,不再需要B*的列表。

顾名思义,我无法控制third_party

目前我有这样的东西。

void call_third_party(const vector<A*>& as) {
    vector<unique_ptr<B>> allocated_bs;
    vector<B*> bs;
    vector<A*>::iterator it;
    for (it = as.begin(); it < as.end(); it++) {
        unique_ptr<B> b(new B(*it));
        allocated_bs.push_back(b);
        bs.push_back(b.get());
    }
    third_party(bs);
}

以防这有帮助。下面是B的构造函数和third_party的签名。

void third_party(const vector<B*>& bs);
B(A* a);

有没有更好、更习惯的方法来做这件事?

void call_third_party(const vector<A*>& as)
{
   std::vector<B> b(as.begin(), as.end());
   std::vector<B*> bp(b.size());
   std::transform(b.begin(), b.end(), bp.begin(), [](B& b) { return &b; });
   third_party(bp);
}

Would

// change name to held_b or something?
vector<B> allocated_bs;
// ...
for(...) {
    auto emplaced = allocated_bs.emplace(allocated_bs.end(), *it);
    bs.push_back(&*emplaced);

可能吗?

Boost的ptr_vector可能会使这更简单。

恕我冒昧,仅仅为指针分配第二个向量似乎有点多-令人震惊的恐怖,为什么不采用老式的方式呢?

template <typename PtrContainer>
struct auto_delete
{
  ~auto_delete()
  {
    for(auto it = _cont.begin(); it != _cont.end(); ++it)
      delete *it;
  }
  PtrContainer& _cont;
};
void call_third_party(const vector<A*>& as)
{
  std::vector<B*> allocated_bs;
  allocated_bs.reserve(as.size());
  // this will take care of cleanup - irrespective of where the exit point is
  auto_delete<std::vector<B*>> dt = { allocated_bs }; 
  (void)dt;
  for(auto it = as.begin(); it != as.end(); ++it)
    allocated_bs.push_back(new B(*it));
  third_party(allocated_bs);
}