List Iterator Access Violation
I have a list
of pointers to SomeClass
objects in a Main
class. Whilst in Main
I can iterate over the list
using list::begin()
and list::end()
.
When I do the same from an instance of SomeClass
(bearing in mind that the list
is a public member of the Main
class) I get the following exception:
0xC0000005: Access violation reading location 0xbaadf0ad.
I am fairly new to coding in C++ coming from a Python background, so I apologise if something doesn't make sense.
Here is an example of the situation:
EDIT: The Main class codes is not actually inside the constructor, its in a method called InitialiseObjects()
.
EDIT: The exceptions comes from within the list::being()
method with the line return (iterator(_Nextnode(_Myhead), this));
#include <list>
using namespace std;
class Main
{
public:
Main::InitialiseObjects()
{
// Execution starts here
SomeClass someClass = new SomClass(this);
someClasses.push_back(someClass);
// This works fine
for (list<SomeClass*>::iterator it = someClasses.begin(); it != someClasses.end(); it++)
...
someClass->AFunction();
}
list<SomeClass*> someClasses;
}
class SomeClass
{
public:
SomeClass::SomeClass(Main *main) : main(main) {}
void SomeCla开发者_JAVA技巧ss::AFunction()
{
// This will not work throwing the aformentioned error
for (list<SomeClass*>::iterator it = main->someClasses.begin(); it != main->someClasses.end(); it++)
...
}
private:
Main *main;
}
0xC0000005: Access violation reading location 0xbaadf0ad.
I think that was 0xbaadf00d
until you overwrote something in it, which indicates uninitialized heap memory. So, maybe you're dereferencing a non-existant Main*
? E.g. main->someClasses.begin()
may throw your exception, if main
wasn't initialized yet.
And indeed, this is the problem in your code. someClass->AFunction();
calls the function while you're inside the Main
-constructor. As such, this
will not be completely valid yet, so you can't use it inside the AFunction
.
As long as you remain inside the Main
constructor, the this
instance is not yet fully initialised!
Trying to access the instance from elsewhere leads to undefined behaviour. This is happening here since you are accessing this unfinished instance from within SomeClass
.
精彩评论