Anne Quinn
Anne Quinn

Reputation: 13002

Will the members of a union member call their own destructors in this scenario?

Will a class with an empty dtor, call it's member's dtors when it's own is explicitly called from within a union?

This is kind of tough to word, hopefully the psuedo-code is more straight-forward. In this example, would Texture::~Texture() call source.bitmap.pixels.~vector() implicitly?

struct Bitmap{
    ~Bitmap(){} // empty dtor

    // members
    std::vector<uint8> pixels;  // <-- will this dealloc when ~Bitmap() is called manually?
};

struct Texture{
    ~Texture(){
        // assume sourceType is 1
        switch(sourceType){ 
        case 1:
            source.bitmap.~Bitmap();
            break;
        }
    }

    // members
    uint sourceType;
    union Source{
        Source(){}
        ~Source(){}

        // members
        Bitmap bitmap;
    }source;
};

Upvotes: 0

Views: 64

Answers (2)

Oblivion
Oblivion

Reputation: 7374

Yes it will implicitly call the destructors of all members and if your class was derived from another class it will call destructor of the base class too.

Upvotes: 1

M.M
M.M

Reputation: 141554

Execution of a destructor is defined to execute the body of the destructor function, and then also execute calls to destructors of members and bases . The pseudo-destructor call executes the destructor.

So yes, the pseudo-destructor call will correctly destroy pixels in this case.

Upvotes: 1

Related Questions