sim642
sim642

Reputation: 769

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?

Upvotes: 2

Views: 5711

Answers (5)

vz0
vz0

Reputation: 32923

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];

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254561

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()};

Upvotes: 3

Mooing Duck
Mooing Duck

Reputation: 66932

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;
}

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

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;

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477228

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.

Upvotes: 2

Related Questions