Static assertion static_assert

Article link: https://subingwen.cn/cpp/static_assert/

1. Affirmations

断言(assertion)It is a common method in programming. Under normal circumstances, 断言就是将一个返回值总是需要为真的判断表达式放在语句中,用于排除在设计的逻辑上不应该产生的情况.

For example: a function always needs to input a parameter within a certain range, then the programmer can use an assertion on the parameter to force the program to exit when an exception occurs in the parameter, so as to avoid the program from falling into logical chaos.

In some senses, assertions are not necessary for normal programs, but for program debugging, assertions can usually help program developers quickly locate program errors that violate certain preconditions.

If we want to use assertions in C++ programs, we need to include header files in the program <cassert>or <assert.h>, the header files provide us with the assert macro for assertion at runtime. for example:

#include <iostream>
#include <cassert>
using namespace std;

// 创建一个指定大小的 char 类型数组
char* createArray(int size)
{
    
    
    // 通过断言判断数组大小是否大于0
    assert(size > 0);	// 必须大于0, 否则程序中断
    char* array = new char[size];
    return array;
}

int main()
{
    
    
    char* buf = createArray(0);
    // 此处使用的是vs提供的安全函数, 也可以使用 strcpy
    strcpy_s(buf, 16, "hello, world!");
    cout << "buf = " << buf << endl;
    delete[]buf;
    return 0;
}

On line 9 of the program, an assertion is used assert(expression), which is a macro whose parameter is an expression, which usually returns a Boolean value and requires, otherwise it 表达式必须为 true 程序才能继续向下执行will directly break.

  • If the createArray parameter is greater than 0, the program runs normally on line 16 until the end
  • If the createArray parameter is less than or equal to 0, the program runs to line 16 and exits directly, and you will see the prompt information as shown below:

insert image description here

2. Static assertions

In the above example we used assert assertion. But assert是一个运行时断言, that is it 只有在程序运行时才能起作用 . This means that we have no way of knowing whether certain conditions are true without running the program. For example: we want to know whether the current platform is 32-bit or 64-bit. For this requirement, we should get the result before the program runs. It is obviously impossible to use assertions. In this case, we need to use C++ 11 静态断言were offered.

Static assertion static_assert, the so-called 静态就是在编译时就能够进行检查的断言, does not need to refer to the header file when used. Another benefit of static assertions is that 可以自定义违反断言时的错误提示信息. Static assertion is very simple to use, it accepts two parameters:

  • 参数1:断言表达式,这个表达式通常需要返回一个 bool值
  • 参数2:警告信息,它通常就是一段字符串,在违反断言(表达式为false)时提示该信息

Due to the discrepancy between the byte size calculated based on VS and the theoretical value, the following program is tested based on 64-bit Linux and uses static assertions to verify whether the current operating system is 32-bit:

// assert.cpp
#include <iostream>                                         
using namespace std;
  
int main()
{
    
    
    // 字体原因看起来是一个=, 其实这是两个=
    static_assert(sizeof(long) == 4, "错误, 不是32位平台...");
    cout << "64bit Linux 指针大小: " << sizeof(char*) << endl;
    cout << "64bit Linux long 大小: " << sizeof(long) <<endl;
  
    return 0;
}

Compile the program with g++:

$ g++ assert.cpp -std=c++11
assert.cpp: In function ‘int main()’:
assert.cpp:6:5: error: static assertion failed: 错误, 不是32位平台...
static_assert(sizeof(long) == 4, "错误, 不是32位平台...");

Since the Linux used is 64-bit, the static assertion detection condition fails during the compilation phase, and the error message prompted is the string corresponding to the second parameter we specified for the static assertion.

If we modify the conditional judgment of the static assertion:

static_assert(sizeof(long) == 8, "错误, 不是64位平台...");

Then compile:

$ g++ assert.cpp -std=c++11

After the compilation is passed, the executable program is obtained a.out, and then the program can be executed to see the following output:

$ ./a.out 
64bit Linux 指针大小: 8
64bit Linux long 大小: 8

If the static assertion condition is judged to be true, the program can continue to execute downward.

Note:
due to 静态断言的表达式是在编译阶段进行检测,所以在它的表达式中不能出现变量,也就是说这个表达式必须是常量表达式.

Guess you like

Origin blog.csdn.net/weixin_38346042/article/details/131509863