简体   繁体   English

调用struct默认析构函数?

[英]Invoking struct default destructor?

In C++, since you can have class-instances as members in structs, the compiler has an implicit destructor just like classes to clean them up. 在C ++中,由于可以将类实例作为结构中的成员,因此编译器具有隐式析构函数,就像清理它们的类一样。 I can invoke a destructor of a class when I allocate an object into my own memory with the fixed-memory new-operator and need to clean it up, but what if I allocate a struct the same way? 当我使用固定内存new-operator将对象分配到自己的内存中并需要清理时,可以调用类的析构函数,但是如果我以相同的方式分配struct怎么办? I know one workaround is to call the destructor of each class instance in the struct, just wondering if there was a way. 我知道一种解决方法是调用结构中每个类实例的析构函数,只是想知道是否有办法。

The same rules that apply to classes also apply to structs. 适用于类的相同规则也适用于结构。 The only difference between class and struct is the default access level, and no other. classstruct之间的唯一区别是默认访问级别,其他都没有。

There's no difference; 没有区别 class and struct are essentially identical: classstruct本质上是相同的:

class Bar { /* .. */ };

struct Foo
{
    Bar x;
};

char arena[HUGE];

Foo * p = ::new (arena) Foo;  // construct
p->~Foo();                    // destroy; calls the destructor for p->x as expected

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM