[英]What happens to members of a stack-allocated class put down with placement new on scope end?
我有這個(編譯)代碼:
#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);
}
編譯器是否處理了 A 和 B 中的向量? Afaik 要銷毀像 A 和 B 一樣分配的 object,我必須顯式調用析構函數。 我在這里不這樣做,我想知道當 scope 結束時,是否仍然為 A 和 B 的成員向量調用析構函數。 這當然是必要的,因為他們管理堆資源。
將它們包含在一個包羅萬象的結構中,如下所示:
#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.