简体   繁体   English

堆栈分配的 class 的成员在 scope 端放置新位置时会发生什么情况?

[英]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.

相关问题 指向堆栈分配对象的指针和引用 - Pointers and references to stack-allocated object 删除std :: lock_guard相对于其他堆栈分配对象的顺序/速度? - delete order/speed of std::lock_guard relative to other stack-allocated objects? 将变量移至外部作用域时,堆栈会发生什么情况? - What happens to the stack when moving a variable to an outer scope? 使用函数分配内存时会发生什么? - What happens when Memory is allocated using a function? 有没有一种方法可以使用placement new将堆栈的对象分配给分配的内存? - Is there a way to assign a stacked object to the allocated memory using placement new? 如果右值引用超出范围会怎样? - What happens if a rvalue reference goes out of scope? 有时,该类必须“默认复制c&#39;tor”? 当我做“新类型[..]”时会发生什么? - There are times so that class must “default copy c'tor” ? and what is happens while I doing “new Type[..]”? 如果我通过引用捕获局部变量会发生什么,并且它超出范围? - What happens if I capture a local variable by reference, and it goes out of scope? 以前有关新作业的数据会怎样? - What happens to previous data on new assignment? 使用指针删除未分配的新内容 - Deleting what wasn't allocated with new using pointers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM