【问题标题】:Converting malloc to new or std::vector将 malloc 转换为 new 或 std::vector
【发布时间】:2019-11-24 18:48:25
【问题描述】:

我无法将 malloc 从我的 c 代码转换为使用 new 的 c++ 方式。我还阅读了有关使用 std::vector 进行动态内存分配的信息。哪一个更适合我的情况,您将如何正确执行此操作?

当前代码:

matrix_t * matrix = (matrix_t *) malloc(sizeof(matrix_t));

我尝试过的:

matrix_t * matrix = new matrix_t[matrix_t];

我得到的错误:

error: expected primary-expression before ‘]’ token
    matrix_t * matrix = new matrix_t[matrix_t];
                                             ^

【问题讨论】:

  • 对于某些 const N 来说是 matrix_t 类似于 typedef double[N][N] matrix_t 吗?
  • 这将有助于提供更多有关情况的背景信息,并解释为什么您将当前代码(分配 1 个矩阵)更改为尝试分配矩阵数组

标签: c++ dynamic-memory-allocation


【解决方案1】:

试试:

matrix_t * matrix = new matrix_t;

比如说一个包含 100 个项目的数组:

matrix_t * matrix = new matrix_t[100];

并通过 std::vector: 做同样的事情:

 std::vector<matrix_t> matrices(100);

虽然 std::vector 可以随时调整大小

 std::vector<matrix_t> matrices;
 matrices.resize(100);

【讨论】:

    【解决方案2】:

    现在是这样的

    auto matrix = std::make_unique<matrix_t>();
    

    参考https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique

    【讨论】:

    • 这是 c++14 吗?我正在使用 g++ 编译,所以我认为它不会允许我使用它,因为我最多只能使用 c++11。
    • 嗯,g++ 甚至知道 C++20。是的,它是 C++14。在此之前使用较少错误安全的形式std::unique_ptr&lt;matrix_t&gt; matrix(new matrix_t);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2016-03-31
    相关资源
    最近更新 更多