2

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?

1
  • As @Mike Seymour figured out, you probably don't understand what you need correctly. Commented Nov 3, 2011 at 17:00

5 Answers 5

3

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()};
Sign up to request clarification or add additional context in comments.

2 Comments

Ahh, someone who read up the background to the OP's question ... and unsurprisingly discovered that the OP didn't know what she needed! +1 for that. (The Fundamental Problem of Life is seeing through what people say they want and discover what they need. I think the Rolling Stones figured that out way before usability analysts became popular.)
Thanks for this nice STL solution.
2

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.

4 Comments

What is the purpose of the parenthesis around *pbrr? Thanks!
Sorry, forgot to add that I need the array to be dynamically-allocated.
Step 3: Profit! (sorry, old cliché)
@sim642: A dynamic array of constants is only possible in C++11, since you need uniform initialization to initialize it: const int * p = new int[3] { 1, 2, 3 };.
1

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

Comments

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;

Comments

0

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

1 Comment

Sorry, forgot to add that I need the array to be dynamically-allocated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.