, 同时满足一个 constnt 表达式?,c++,constant-expression"/>

首页 > 解决方案 > 如何将整数传递给指针,传递给 std::array, 同时满足一个 constnt 表达式?

问题描述

我有一个函数noise.cpp,目前的形式是,

double* noise(int* steps, ...)

//some code

std::array<double, *steps> NoiseOut;

//rest of code

正在由 cppnoise.cpp 测试和访问,

#include <random>
#include <cmath>
#include<stdio.h>
#include <iostream>
#include "noise.h"

main(){

    double* out;

    int steps = 8;
    int* ptr = &steps;

    out = noise(ptr, 1, 1000, 0.1, 1, 3);
    printf("TEST \n");
    std::cout << out[0];

}

带头文件,

extern double* noise(int*, double, double, double, double, double); 

以前,我通过 Python 访问了 NoiseOut 数组最初所在的 noise.cpp 函数,double* NoiseOut = new double[steps];结果很理想,但是这种方法导致了内存泄漏。

最初我尝试删除分配的内存。但是该函数返回 NoiseOut,所以我不确定这是否可能?因此,相反,我发现现代方法是使用 std::array ,因为它带有某种形式的垃圾收集。如果我尝试这样做,

double* noise(int steps, ...)

std::array<double, steps> NoiseOut;

有人告诉我,steps 不是一个固定的表达方式。我尝试了各种方式constexpr,但是conststatic没有成功。通常会出现同样的错误error: ‘steps’ is not a constant expression。另外,我将指针从 cppnoise.cpp 传递给 noise.cpp 的原因是因为我在某个地方读到了指针更容易使用的地方,后来在编译时?这样也许我可以将其转换为常量表达式?大概是发烧的梦吧。

那么,如何在程序中声明一个整数值,并将其传递给一个函数,该函数可用于 std::array 而不会导致该错误?

注意:我对 c++ 非常陌生,主要使用 SQL、Python、R 和 SageMath。

标签: c++constant-expression

解决方案


std::array is ill suited for this because you don't know what size you need until the code runs. std::array needs to know the size when it is compiled.

Using new gives a dynamic array size at run time, which is why you could use it before.

If you are concerned about memory leaks (or actually, in general), then I suggest using an std::vector instead:

#include <vector>
//...
std::vector<double> NoiseOut;
NoiseOut.reserve(*steps);

An std::vector should allow you to do most everything an std::array or C Array would allow you to so, though I suggest reading up on its documentation (linked above). Note that std::vector also comes with its own garbage collection of sorts in the same way std::array does.


推荐阅读