[英]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?编译器是否处理了 A 和 B 中的向量? Afaik to destroy an object allocated like A and B, I would have to call the destructor explicitely. Afaik 要销毁像 A 和 B 一样分配的 object,我必须显式调用析构函数。 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.我在这里不这样做,我想知道当 scope 结束时,是否仍然为 A 和 B 的成员向量调用析构函数。 This is of course necessary as they manage heap ressources.这当然是必要的,因为他们管理堆资源。
Contain them into an encomassing 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.