samedi 9 septembre 2017

Calling a virtual function of a union data member through a pointer results in a segmentation fault

I have an instance of a class that I'm storing in a union. When I call a virtual function of the class through a pointer to the union member, I get a segmentation fault. I suspected that my code might not work but to what things (e.g. part of the standard or something similar) should I pay attention in this situation? I tested with Clang++ 3.9.0 and GCC 7.2.0 in C++11 mode.

#include <iostream>

struct test_class
{
    virtual void virtual_do_stuff()
    {
        std::cerr << "Doing stuff (virtual)." << std::endl;
    }

    void non_virtual_do_stuff()
    {
        std::cerr << "Doing stuff (non-virtual)." << std::endl;
    }
};


union un
{
    int a;        // Dummy.
    test_class c;

    ~un() {}
    un() {}
};


int main(int argc, char **argv)
{
    un u;

    test_class c;
    test_class *cptr(&c);
    cptr->virtual_do_stuff();

    u.c = std::move(c);
    u.c.virtual_do_stuff();

    test_class *cptr2(&u.c);
    cptr2->non_virtual_do_stuff();
    cptr2->virtual_do_stuff();      // Causes the segmentation fault.

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire