[英]Access violation when accessing vector element's member function
I am coding an MFC applcation using VS2012. 我正在使用VS2012编写MFC应用程序。
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. 我有一个
Bitmap*
的向量,我在for循环中插入了元素,然后,如果我尝试在循环外访问某些元素的函数,则会导致访问冲突。
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. 在两个示例中,
m_VectorImageNames
都已经填充了一些图像文件路径,这不是问题。
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: 如果我将
GetWidth
放入循环中,它将返回正确的值:
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: 我已经尝试了一些方法,但没有成功:
Does anyone have a clue of what may be happening? 有谁知道可能会发生什么?
The BitMap object img
is defined on the stack inside the loop. BitMap对象
img
在循环内的堆栈上定义。 The pointer to img
is pushed into the vector. 指向
img
的指针被推入向量。 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. 使用
new
(用于动态内存分配的运算符)存储位图。
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
. 可能更好的方法(而不是使用原始指针)是使用内存管理的指针,例如
std::shared_ptr
。 This depends on your requirements. 这取决于您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.