简体   繁体   English

在C ++库中使用动态内存分配

[英]Using dynamic memory allocation with C++ Libraries

I'm trying to use Alglib's spline functions and in order to do that I have to initialize an array with my data and pass it in to Alglib's spline function. 我正在尝试使用Alglib的样条函数,为此,我必须使用我的数据初始化一个数组并将其传递给Alglib的样条函数。

I keep getting n_c has to be a constant error. 我不断得到n_c必须是一个恒定的错误。 Is there any way around this? 有没有办法解决? I'm already using vector for points. 我已经在使用矢量积分了。 The size wont change when I'm building my spline. 建立样条线时,尺寸不会改变。

void Connector::UniformSpacing(int n)
{
    double arcL = Length();
    double ds = arcL / ((double)n);
    static const int n_c = points.size();
    alglib::real_1d_array x[n_c]; // Error here, n_c is still not a constant

    alglib::spline1dbuildcubic()
}

Just because the variable is a static const object on the stack doesn't mean that it is a compile-time constant: the variable is initialized at run-time when the function is first called. 仅仅因为变量是堆栈上的static const对象,并不意味着它是编译时常量:变量在运行时在首次调用该函数时初始化。 However, for a built-in array the size needs to known at compile-time. 但是,对于内置数组,大小需要在编译时知道。 You can make it a constexpr in which case the compiler will refuse to compile the initialization unless it can be figured out during compile-time. 您可以将其设为constexpr在这种情况下,除非可以在编译期间确定初始化,否则编译器将拒绝编译初始化。

The easiest way to use a run-time size is to use 使用运行时大小的最简单方法是使用

std::vector<alglib::real_1d_array> x(n_c);

For this type it isn't necessary to know the size at compile-time. 对于这种类型,不必在编译时知道大小。

n_c必须是编译时间常数。

If you need an array whose size can only be specified at runtime, you need to use one of the myriad dynamically sizeable constructs. 如果需要只能在运行时指定其大小的数组,则需要使用无数动态可调整大小的结构之一。 Depending on whether or not you want to pass ownership of this newly allocated array to the calling library, use one of these two constructs: 根据是否要将此新分配的数组的所有权传递给调用库,请使用以下两种结构之一:

std::unique_ptr<alglib::real_1d_array[]> x(new alglib::real_1d_array[n_c]);
  1. Pass ownership to calling library function(say libfunc ) - You would call release on the unique_ptr and call as follows : libfunc(x.release()) . 将所有权传递给调用库函数(例如libfunc )-您将在unique_ptr上调用release ,并按如下所示进行调用: libfunc(x.release())
  2. Retain ownership - libfunc(x.get()) . 保留所有权libfunc(x.get())

Of course, in the "Retain ownership" case, the assumption is that the library won't free this memory. 当然,在“保留所有权”的情况下,假设是该库不会释放此内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM