1

I have a set of pointers to image block objects. I have a derived class member function that returns a pointer to one of these image blocks, it is a virtual function so I can't change the return type without breaking everything.

Here is what I have so far:

ImageBlock* objArray = static_cast<ImageBlock*>( ::operator new ( sizeof ImageBlock * 256 ) );

for ( int i = 0; i < 256; i++ )
    new (&objArray[i]) ImageBlock(blkh, blkw, 0.0);

for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 16; j++) {
        ImageBlock* temp = getNewBlock(i, j, Image); // getBlock returns ImageBlock*
        objArray[i*16 + j] = *temp;
        delete temp;
    }
}

As you can see this is a terrible solution. I'd like to assign the pointer directly using some pointer arithmetic like so:

for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 16; j++) {
        (objArray+(i*16 + j)) = getNewBlock(i, j, Image);
    }
}

However I get the error expression must be a modifiable lvalue with objArray underlined in red. I know it would work the other way around taking a pointer from the array. I've searched the error and I keep seeing things like "you can't assign to arrays" well it isn't an array in the conventional sense is it? I have a few thoughts on why it won't work but I would like to know for sure. If anyone could offer up a better solution that would be interesting.

Thanks

1
  • 1
    Ivalue, you mean lvalue. Commented Jan 26, 2014 at 0:27

1 Answer 1

2

If you would like to assign pointers, you need to create an array of pointers. What you have is an array of ImageBlock objects, so the solution that you provided, i.e.

objArray[i*16 + j] = *temp;

is perfectly fine. If you would like to make an array of pointers, you need to declare and use it differently:

ImageBlock** objPtrArray = new ImageBlock*[256];

Now you can make an assignment using square bracket notation:

objPtrArray[i*16 + j] = getNewBlock(i, j, Image);

Of course it is now your responsibility to delete elements of objArray.

A better solution would be to use a vector of smart pointers. This would free you up from the chores of explicit memory management:

vector<unique_ptr<ImageBlock> > objVector(256);
...
objVector.push_back(unique_ptr<ImageBlock>(getNewBlock(i, j, Image)));
Sign up to request clarification or add additional context in comments.

1 Comment

I used the double pointer notation. The project I'm doing is simple however I would prefer to learn more about memory management and the logic of it all. Using it definitely reduced the amount of code I had. Thank you, I will look into vectors if I have the time.

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.