gpt4 book ai didi

C++ 模板 : check if a type's destructor can be "ignored"

转载 作者:行者123 更新时间:2023-11-30 01:01:38 24 4
gpt4 key购买 nike

首先,让我更具体地说明这个问题。

通过说

check if a type's destructor can be "ignored"

我是坏人

check if a class has no side effects when it's instances die.

我在做什么:

我正在为我们的 C++ 项目编写垃圾收集库,我需要提高性能。如果我能检测到传入的类型T在销毁时没有副作用,我就可以只检查所有活的对象,其余的都是垃圾,可以标记为“垃圾”(典型的年轻代收集技术)。但如果它有副作用,我必须扫描每一个垂死的对象并运行它的析构函数。

例如:

struct S1 {
int i;
}; // can be ignored

struct S2 {
int i;
~S2() {

}
}; // can be ignored

struct S3 {
S3() {
std::cout << "S3()" << std::endl;
}
virtual ~S3() {
std::cout << "~S3()" << std::endl;
}
}; // can not be ignored, destructor has side effect

struct S4 {
S3 s3;
}; // can not be ignored, destructor has side effect(calling s3's destructor)
// this is the most tricky one I tried and failed.

struct S5 {
S3 s3;
~S5() {

}
}; // same with S4

struct S6 : public S3 {

};// can not be ignored, super destructor has side effect

struct S7 : public S1 {

};// can be ignored, super destructor does not have side effect

struct S8 {
virtual ~S8() = default;
}; // can be ignored
// which cannot use is_trivially_destructible

struct S9 : public S8 {

}; // can be ignored

我试过将is_destructibleis_trivially_destructible结合起来,但这两个不能满足我的要求。特别是示例 4。

此外:欢迎任何可以解决此问题的编译器特定功能。

最佳答案

std::is_trivially_destructible类型特征是你所需要的。看here .输出与预期不同的唯一情况是 S2。不幸的是,C++ 缺乏将空的用户定义的析构函数视为微不足道的结构。

编辑:

没有办法从上面的特征中排除虚拟的条件,所以剩下的唯一选择就是创建你自己的特征。这需要在用户端做额外的工作,而不是开箱即用。有几种方法可以用自定义谓词来区分用户定义的类型:

  1. 通过某种类型的继承:

    class my_class : private can_be_forgotten_tag { ... };

    template <typename T>
    using can_be_forgotten_v =
    std::is_trivially_destructible<T> ||
    std::is_base_of<can_be_forgotten_tag, T>;
  2. 通过presence of a member (例如,类型别名 - 标签 - transparent comparators 是如何定义的)

  3. 根据模板特化(不限于 1. 和 2.):

    template <typename T>
    struct can_be_forgotten : std::is_trivially_destructible<T> {};

    template <>
    can_be_forgotten<S8> : std::true_type {};
  4. 也许更多...

更重要的是,首先应该问的问题是,这是否已经不是任何编译器自动为您做的事情(生成相同的代码,有或没有析构函数调用)。那个,最好自己检查一下。

附言我希望我们一直在考虑 placement-new,否则会出现内存泄漏。

关于C++ 模板 : check if a type's destructor can be "ignored",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58763276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com