glades
glades

Reputation: 4848

What happens to members of a stack-allocated class put down with placement new on scope end?

I have this (compiling) code:

#include <iostream>
#include <vector>

class Base {
    std::vector<Base*> handles_;

public:
    Base(Base* handle) : handles_( {handle} ) { };
};

class A : public Base {
    using Base::Base;
};

class B : public Base  {
    using Base::Base;
};

int main()
{
    A* addr_of_A = (A*)alloca(sizeof(A));
    B* addr_of_B = (B*)alloca(sizeof(B));

    new (addr_of_A) A(addr_of_B);
    new (addr_of_B) B(addr_of_A);
}

Are the vectors inside A and B taken care of by the compiler? Afaik to destroy an object allocated like A and B, I would have to call the destructor explicitely. I'm not doing that here and I'm wondering if the destructor is still called for the member vectors of A and B when scope ends. This is of course necessary as they manage heap ressources.

Upvotes: 0

Views: 38

Answers (1)

datenwolf
datenwolf

Reputation: 162297

Contain them into an encompassing struct like this:

#include <iostream>
#include <vector>

class Base {
    std::vector<Base*> handles_;

public:
    Base(Base* handle) : handles_( {handle} ) { };
};

class A : public Base {
    using Base::Base;
};

class B : public Base  {
    using Base::Base;
};

int main()
{
    struct C {
        A a;
        B b;
        C() : a(&b), b(&a) {}
    } c;
}

Upvotes: 1

Related Questions