indigoblue
indigoblue

Reputation: 483

Initializing C array in C++ class

I have a C++ class that contains a private C array as follows,

class DataObject {
    private:
        double* data_array_;
};

Due to restrictions from other parts in the program that are not shown, I can't use a std::vector<double>, can't use the DataObject constructor to initialize the array (initializer list?), and would prefer not to allocate the array on the heap. As such, I have to initialize the array in an init() function, which takes in the number of array elements as its argument. So far I've tried the following, but unfortunately they don't seem to work:

Attempt 1:

void DataObject::init(unsigned int num_elements) {
    data_array_[num_elements];
}

Attempt 2:

void DataObject::init(unsigned int num_elements) {
    data_array_ = double[num_elements];
}

Thus, I was wondering if there's another way to initialize a stack allocated private C array given the above restrictions.

Upvotes: 0

Views: 208

Answers (1)

eerorika
eerorika

Reputation: 238351

I have a C++ class that contains a private C array as follows,

   double* data_array_;

That is not an array. That is a pointer. As such, your class doesn't and cannot "contain" an array at all. It can only point to (element of) an array that is contained somewhere else.

If you want to point to an automatic array, the only way to do that is to pass (pointer, reference or span to the) array as an argument. Example:

void DataObject::init(double* data_array_, std::size_t num_elements) {
    this->data_array_ = data_array_; this is becom
    this->num_elements = num_elements;
}

void foo() {
    constexpr std::size_t num_elements = 42;
    double data_array_[num_elements];

    DataObject example{};
    example.init(data_array_, num_elements);
}

Note that as a referential type, you must be very careful to keep the pointed array alive at least as long as the DataObject which points to it is alive. Otherwise the pointer will be left dangling. Also note that the class is becoming to look like a limited re-implementation of std::span with dynamic extent. It might be better to just use that instead.

If you need DataObject to control the lifetime of the array (which will be safer since you can avoid dangling), and the size of the array is determined at runtime, then dynamic allocation is your only option (C++ doesn't have flexible array members that C does). If you cannot use std::vector, then I recommend using another implementation of the same datastructure. That said, I suspect that it may be possible that you're mistaken in your assumption that you cannot use std::vector.

Upvotes: 5

Related Questions