c++ - 我可以在不使用原始指针的情况下避免在 std::initializer_list 初始化期间进行复制吗?

标签 c++ shared-ptr initializer-list

假设我有几个在本地声明的对象,我想使用基于范围的 for 语法对其进行迭代。这似乎运作良好,但是,似乎要将本地对象放入 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;
}

有没有办法在不复制或诉诸使用原始指针的情况下迭代一组本地声明的对象?

最佳答案

您可以使用 std::ref构建 std::reference_wrapper 列表。这会隐藏指针并让您像这样编写列表

for(const std::shared_ptr<int>& ptrInt : {std::ref(ptrInt1), std::ref(ptrInt2)}) {
    std::cerr << *ptrInt << std::endl;
}

关于c++ - 我可以在不使用原始指针的情况下避免在 std::initializer_list 初始化期间进行复制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54868996/

相关文章:

c++ - 带有 boost::shared_ptr 的空指针?

c++ - 为什么 'std::vector<int> b{2};' 创建一个 1 元素 vector ,而不是 2 元素 vector ?

c++ - 混合 C++ 类继承和初始化列表。我心中的未解之谜

c++ - Physical Boost.Units 用户定义文字

c++ - 从文件读取时tellg() 的行为如何?

c++ - 用 C++ 实现 Bridesearch

c++ - c++11 中的 intrusive_ptr

c++ - 在两个 lambda 之间共享对象

c++ - 为什么 GCC 6.3 在没有明确 C++11 支持的情况下编译这个 Braced-Init-List 代码?

c++ - 使用多线程处理 Qt 应用程序中的升压信号