【问题标题】:How to initialize a shared_ptr as an array of int in C++如何在 C++ 中将 shared_ptr 初始化为 int 数组
【发布时间】:2023-01-19 01:05:31
【问题描述】:

我有一个这样定义的类变量:

std::shared_ptr<int[]> variable;

我想让它存储从 0 到 10 的整数

这样当我调用 variable[1] 时它返回 1 等等。

【问题讨论】:

  • 为什么不使用 std::vector 呢?
  • std::make_shared&lt;int[]&gt;(sizeOfArray); godbolt.org/z/rcnc8K9Ko 但使用 std::vector 更方便。
  • 你描述了你想如何解决某事,但也许如果你告诉我们你想做什么,我们可以给出更好的答案。
  • 如果要存储一个值,请使用 int。如果你想存储多个整数并且你现在在编译时数组的大小使用std::array&lt;int,size&gt;。如果您的数组可以在运行时增长,请使用std::vector&lt;int&gt;。数组和向量具有移动语义,您可以通过(常量引用)将它们传递给函数,因此您几乎不需要指向它们的指针(智能与否)
  • 您可能需要 this 和 std::vector 或 std::array

标签: c++ arrays dynamic-memory-allocation boost-smart-ptr


【解决方案1】:

我会像这样使用 std::array 语法

#include <array>
#include <iostream>
#include <memory>

int main()
{
    // use the std::array syntax it will make the dereferenced smartpointer
    // directly behave like an array. You can use index operator and even
    // use it in range based for loops directly
    auto variables = std::make_shared<std::array<int, 10>>();

    for (std::size_t n = 0ul; n < variables->size(); ++n)
    {
        (*variables)[n] = n;
    }

    for (const int value : *variables)
    {
        std::cout << value << " ";
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 2017-05-30
    • 1970-01-01
    • 2013-08-02
    相关资源
    最近更新 更多