0xC0000005: Access Violation in C ++

Here is my code:

class Base
{
public:
    virtual void show() const = 0;
};

class Child : public Base
{
private:
    static const int i = 1;
public:
    virtual void show() const
    {
        cout << i;
    }
};

map<int, const Base &> myMap{
    { 0, Child() },
    { 1, Child() },
};

Base & b = Child();

int main()
{
    b.show();

    myMap.at(0).show(); // This provokes the error

    system("pause>NUL");
    return 0;
}

      

As you can see I am trying to use data global

(or static

) which will call some functions virtual

. When I test Base & b = Child();

and at main

: b.show();

everything goes well.

But if I use map

as above, I get the error:

0xC0000005: Access violatoin reading location 0x00000000

...

I tried to debug this code and I found that when it arrived myMap.at(0).show();

I got this:
enter image description here

Seems like the virtual function table Unable to read

...

Then I tried using the pointer:
map<int, Base *>

and {0, new Child()}

.
It works.

So it seems that this error is coming from a temporary link.

But I don't know why it works b

. b

is also a temporary link.
In my opinion, it map

contains a lot b

.
Why does it work b

, then how map

does it not work?

+3


source to share


2 answers


You have a temporary link map. I'm surprised that even compiled

map<int, Base &> myMap{
    { 0, Child() },
    { 1, Child() },
};

      

Drop the link and switch to unique_ptr

std::map<int, std::unique_ptr<Base>> myMap;

      



You can insert items into this card using this method . This will prevent objects from breaking up .

You do the same thing again here

Base & b = Child();

      

You cannot hold non-const references to temporary objects

+6


source


MSVC allows temp reference to be influenced, which means it is Base & b = Child();

accepted and handled correctly even if it is not standard C ++ and rejected by other compilers (and later version of MSVC may be rejected)

But even MSVC doesn't accept stl reference containers.



So, you should either use map<int, Base>

(no ref, store a copy of the object) or map<int, Base *>

(store a pointer to the object). In the latter case, you must deal with the destruction of the object. You can also use smart pointers, unique_ptr

or shared_ptr

have stl take care of automatic destruction.

0


source







All Articles