简体   繁体   中英

How to create a dynamically-allocated array of const objects, but have values assigned to them?

I need to create a dynamically-allocated array of const objects. What makes it difficult is that I need to have values assigned to the const objects too.

I need this for Samples variable of this SFML class .

How should I do it?

You don't need an array of const objects. A pointer-to-const can point to either const or non-const objects; you can create a dynamic array and initialise a Chunk structure from it like this:

std::vector<Int16> samples;
initialise(samples);

// valid until 'samples' is destroyed or resized
SoundStream::Chunk chunk = {&samples[0], samples.size()};

Easy:

// Step 1: Make an array of const values:
const int arr[] = { 1, 4, 9, 17 };

// Step 2: Make a pointer to it:
auto        parr     = &arr; // 2011-style
const int (*pbrr)[4] = &arr; // old-style

You cannot "assign" values to constants (obviously), so the only way to endow a constant with a value is to initialize it to that value.

Or, if the data is not known at compile time:

const std::vector<int> function() {
    std::vector<int> tmp(5); //make the array
    for(int i=0; i<5; ++i)
        tmp [i] = i; //fill the array
    return tmp;
}

Should you need a dynamically allocated array, I recommend using a standard container:

std::vector<Int16> data;
Chunk* c = ...;

data.push_back(...);

c->Samples = &data[0];

Do the allocation, assign it to a pointer to non-const. Make your modifications to the data. When you're done muckin' things about, then you can assign your const pointer to the array. For example:

int * p = new int[100];
for (int i=0; i<100; ++i)
    p[i] = i;

const int * cp = p;

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