gpt4 book ai didi

c++ - 析构函数中的奇怪枚举

转载 作者:IT老高 更新时间:2023-10-28 12:01:03 25 4
gpt4 key购买 nike

目前,我正在阅读Protocol Buffer的源代码,发现一个奇怪的enum代码定义here

  ~scoped_ptr() {
enum { type_must_be_complete = sizeof(C) };
delete ptr_;
}

void reset(C* p = NULL) {
if (p != ptr_) {
enum { type_must_be_complete = sizeof(C) };
delete ptr_;
ptr_ = p;
}
}

为什么这里定义了 enum { type_must_be_complete = sizeof(C) };?它是干什么用的?

最佳答案

此技巧通过确保在编译此析构函数时 C 的定义可用来避免 UB。否则编译会失败,因为 sizeof 不完整类型(前向声明的类型)无法确定,但可以使用指针。

在编译后的二进制文件中,这段代码会被优化掉,不会有任何效果。

请注意:删除不完整的类型可能是未定义的行为,从 5.3.5/5 开始:。

if the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

g++ 甚至发出以下警告:

warning: possible problem detected in invocation of delete operator:
warning: 'p' has incomplete type
warning: forward declaration of 'struct C'

关于c++ - 析构函数中的奇怪枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800783/

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