سؤال

I am coding an MFC applcation using VS2012.

I have a vector of Bitmap*, I insert elements in a for loop, and then, if I try to access some element's function outside the loop it will give me an access violation.

The strange thing is if I try to access it inside the loop, it works just fine.

In both examples m_VectorImageNames is already filled with some image files paths, it is not the problem.

The following code gives the access violation (at the last line):

std::vector<Bitmap *> vectorImages;

for (int i = 0; i < nImages; i++) 
{
    Bitmap img(m_VectorImageNames[i]);

    vectorImages.push_back(&img);
}

int imgWidth= vectorImages[0]->GetWidth();

If I put the GetWidth inside the loop, it returns the correct value:

std::vector<Bitmap *> vectorImages;

for (int i = 0; i < nImages; i++) 
{
    Bitmap img(m_VectorImageNames[i]);

    vectorImages.push_back(&img);

    int imgWidth= vectorImages[0]->GetWidth();
}

I have tried a few things already, with no success:

  • Initializing the vector with the size it will have and then inserting each bitmap in its corresponding position (with hope that it was an allocation problem).
  • Looping using iterators
  • Making the vector a class member variable

Does anyone have a clue of what may be happening?

هل كانت مفيدة؟

المحلول

The BitMap object img is defined on the stack inside the loop. The pointer to img is pushed into the vector. Then the memory storage that the pointer elements point to in the vector is lost once the loop has terminated.

Use new (the operator for dynamic memory allocation) to store the bitmaps.

for (int i = 0; i < nImages; i++) 
{
    Bitmap *img = new BitMap(m_VectorImageNames[i]);
    vectorImages.push_back(img);
    ...
}

Possibly better (instead of using raw pointers) would be to use a memory-managed pointer such as std::shared_ptr. This depends on your requirements.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top