简体   繁体   中英

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.

I keep getting n_c has to be a constant error. 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. 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.

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()) .
  2. Retain ownership - libfunc(x.get()) .

Of course, in the "Retain ownership" case, the assumption is that the library won't free this memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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