Skip to content

Instantly share code, notes, and snippets.

@wanghenshui
Last active March 26, 2021 06:46
constexpr1.cpp
#include <numeric>
constexpr int naiveSum(unsigned int n) {
auto p = new int[n];
std::iota(p, p+n, 1);
auto tmp = std::accumulate(p, p+n, 0);
delete[] p;
// 如果这里注释掉delete,会报错
// error: '(naiveSum(10) == smartSum(10))' is not a constant expression because allocated storage has not been deallocated
// 4 | auto p = new int[n];
// 如果改成delete p也会报错
// error: non-array deallocation of object allocated with array allocation
return tmp;
}
constexpr int smartSum(unsigned int n) {
return (n*(1+n))/2;
}
int main() {
static_assert(naiveSum(10) == smartSum(10));
static_assert(naiveSum(11) == smartSum(11));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment