gpt4 book ai didi

c++ - 编译时检查和运行时检查 'at the same time'

转载 作者:行者123 更新时间:2023-12-02 08:12:21 25 4
gpt4 key购买 nike

假设我有以下简化程序:

Link to godbolt.org :

#include <cassert>

struct Dimensions {

Dimensions& operator=(int i) {
assert(i != 0);
return *this;
}

};

int getDim();

int main() {
Dimensions dims;
dims = getDim();//ok, just use runtime assert
dims = 0;//compile error wanted here
return 0;
}

在第一种情况 (getDim) 中,无法检查编译时,因此我们很乐意在运行时检查它。

但是是否也可以在编译时进行检测(对于第二种情况,dims = 0;),当理论上看起来这是可能的? (也许有某种重载或包装器?)

最佳答案

使用 gcc 编译器在 C 中执行的典型方法,也适用于 C++:您使用 __builtin_constant_p内置检查表达式是否是持续评估的,然后检查表达式,然后调用用 __attribute__((__warning__)) 声明的函数或与 __attribute__((__error__)) 。就像这样:

#include <cassert>
#include <type_traits>

#define CONCAT(a, b) a ## b
#define XCONCAT(a, b) CONCAT(a, b)
#define maybe_static_maybe_not_assert(expr) do { \
if (__builtin_constant_p(expr)) { \
if (!(expr)) { \
extern __attribute__((__warning__( \
"static_assert: expression: " #expr " will fail on runtime!" \
))) void XCONCAT(maybe_static_maybe_not_assert_warn, __LINE__)(); \
XCONCAT(maybe_static_maybe_not_assert_warn, __LINE__)(); \
} \
} \
assert(expr); \
} while(0)

struct Dimensions {

Dimensions& operator=(int i) {
maybe_static_maybe_not_assert(i != 0);
return *this;
}

};

int getDim();

int main() {
Dimensions dims;
dims = getDim();
dims = 0;
dims = 1;
return 0;
}

在优化编译时应该发出警告:

In member function 'Dimensions& Dimensions::operator=(int)',
inlined from 'int main()' at <source>:32:12:
<source>:12:70: warning: call to 'maybe_static_maybe_not_assert_warn21' declared with attribute warning: static_assert: expression: i != 0 will fail on runtime! [-Wattribute-warning]
12 | XCONCAT(maybe_static_maybe_not_assert_warn, __LINE__)(); \
| ^
<source>:21:9: note: in expansion of macro 'maybe_static_maybe_not_assert'
21 | maybe_static_maybe_not_assert(i != 0);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compiler returned: 0

就是这样_FORTIFY_SOURCEglibc 中实现.

关于c++ - 编译时检查和运行时检查 'at the same time',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785911/

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