用于动态填充对象并在返回时销毁的c++习语
C++ idiom for dynamically populating objects and destroying at return
我用的是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);
}
相关文章:
- 概念可以与 CRTP 习语一起使用吗?
- 复制和交换习语和迭代器
- 为什么当我做复制和交换习语时不调用我的复制构造函数?
- 漂亮的计数器习语的错误或格式错误的静态订单惨败?
- C++17 pimpl 习语上下文中的自定义迭代器
- 在 MyVector 中实现写入时复制习语
- 视觉 "extern __forceinline "是什么 c++ 习语?
- C 习语使用C库时,该C库期望功能指针
- 为什么 std::swap 不使用 swap 习语?
- 如何使用擦除删除习语从结构向量中删除值
- C++中的Singleton习语
- 在 C++11 中实现复制和交换习语的更好方法
- N 个并发读取器和 1 个生产者的习语或模式
- pImpl习语-将私有类实现放在cpp中有什么缺点
- 不能使用 pimpl 习语将用户定义的向量插入到封装的向量中
- Python -> C++ 习语:将 lambda 表达式存储在映射/容器中
- 安全方便的通用散列(用于 STL 无序集和映射)习语?
- 指向可配置实现的Pimpl习语
- 与构造函数参数相关的异常安全的习语
- 用C++处理身体习语