dimanche 26 novembre 2017

Destruction of a non-existing object

I am struggling a little bit with move semantics. I read a lot about that topic, however, there are two concrete problems to which I did not found any answers and, thus, like to present them to you.

First, I have the following exemplary code:

class A
{
    public:
        A *ptr;
        virtual ~A() 
        { 
            std::cout << "dtor" << std::endl; 
            delete ptr; 
            ptr=nullptr;
        }
};

main()
{
    A x, y;
    x.ptr = &y;
}

Class A is able to have a member of itself. I use this "composite pattern" concept to build a hierarchy. However, in this case, when object x is destructed, its destructor deletes the pointer to object y. When finally object y should be destructed, it is already which yields an error... How can I solve this?

The second case looks like this:

main()
{
    A x, y;
    y = std::move(x);
    std::cout << "x.ptr: " << x.ptr << std::endl;
    std::cout << "y.ptr: " << y.ptr << std::endl;
}

Here, I can see that both references are equal which means both exists. I though that std::move moves the content from x to y. I would have expected that x.ptr is "empty"....?

Thanks in advance!

Cheers

Aucun commentaire:

Enregistrer un commentaire