C++ 虐我千百遍
109 subscribers
31 photos
7 links
Download Telegram
Forwarded from valueless channel
#今天踩了啥坑 #cpp #cpp20
template<size_t i>
consteval void count_to_one() {
if constexpr (i <= 1) {
return;
}

char buffer[i];
if constexpr (i % 2 == 0) {
// ... do something if `i` is even
return count_to_one<i - 1>();
} else {
// ... do something if `i` is odd
return count_to_one<i - 1>();
}
}

int main() {
count_to_one<10>();
}

先试试你能一眼看出代码中的错误吗

尽管走到判断 i 的奇偶处,一定隐含了 i 不会小于等于 1,但在 if constexpr 的上下文中,有无 else 关键字对编译器来说是有区别的 —— if constexpr 上下文以外的代码对于编译器总是可见的(不受编译时常量条件编译),所以上面的代码会导致实例化出 i 下溢出到负数长度的 buffer 数组。

https://godbolt.org/z/nPz9WzxrK