all*_*y87 4 c++ shared-ptr initializer-list
假设我有几个本地声明的对象,我想使用基于范围的语法进行迭代.这看起来效果很好,但是,似乎要将本地对象放入initializer_list,执行复制.对于像这样的对象来说这是个坏消息std::shared_ptr(据我所知),增加引用计数是一个原子操作.我认为可以避免的唯一方法是使用原始指针.
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> ptrInt1 = std::make_shared<int>(1);
std::shared_ptr<int> ptrInt2 = std::make_shared<int>(2);
/* in this loop, ptrInt1 and ptrInt2 are copied before they are binded
to ptrInt, this is ugly since the reference counter needs to temporarily
increased */
for(const std::shared_ptr<int>& ptrInt : {ptrInt1, ptrInt2}) {
std::cerr << *ptrInt << std::endl;
}
/* this solution works, but it feels somewhat ugly having to convert my smart
pointers to raw pointers to avoid the copying, perhaps there is a better
solution ?? */
for(const int* rawPtrInt : {ptrInt1.get(), ptrInt2.get()}) {
std::cerr << *rawPtrInt << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法迭代一组本地声明的对象而不复制它们或使用原始指针?
您可以使用它std::ref来构建std::reference_wrappers 列表.这隐藏了指针,让你像列表一样写
for(const std::shared_ptr<int>& ptrInt : {std::ref(ptrInt1), std::ref(ptrInt2)}) {
std::cerr << *ptrInt << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |