C++ 14 17 New features: [[fallthrough]], [[nodiscard]], [[maybe_unused]], and [[deprecated]] new attribute usage...


1. New attributes added in C++ 14 17

  1. [[fallthrough]] attribute: This attribute is used in the switch statement. Usually, when one of the switch statement is executed, it will automatically jump to the end of the statement, unless there is a> attribute. Tell the compiler that this is intentional behavior to avoid compiler warnings. , you can use the to the next statement. If you want to intentionally "fall through" from one caseswitchbreakcasecase[[fallthrough]]

  2. [[nodiscard]]Attribute: This attribute can be used for functions or return types. Its function is to tell the compiler that when this function is called, its return value should not be ignored. If the programmer calls such a function without using its return value, the compiler issues a warning. This is especially useful for functions that return important status or error codes.

  3. [[maybe_unused]]Attribute: This attribute can be used to declare variables, functions, types, etc. It tells the compiler that even if this entity (variable, function, etc.) is not used, it should not generate an unused warning. This is useful when writing code that may not be used in some situations but is used in others.

  4. [[deprecated]]Attribute: This attribute is used to mark variables, functions, types, etc. as being deprecated. The compiler issues a warning when other code attempts to use an entity that is marked as deprecated. This is typically used for code base migrations and upgrades to alert developers that certain features may be removed or changed in future releases.

2. Example

sure. Below I'll provide a simple example for each property:

  1. [[fallthrough]]Property example:

    switch (value) {
          
          
        case 1:
            //... 一些代码 ...
            [[fallthrough]]; // 明确指出接下来会执行 case 2 的代码
        case 2:
            //... 一些代码 ...
            break;
        default:
            //... 一些代码 ...
            break;
    }
    
  2. [[nodiscard]]Property example:

    [[nodiscard]] int computeValue() {
          
          
        return 42;
    }
    
    void example() {
          
          
        computeValue(); // 这里如果不使用返回值,编译器可能会警告
        int value = computeValue(); // 正确使用返回值
    }
    
  3. [[maybe_unused]]Property example:

    void example([[maybe_unused]] int unusedParam) {
          
          
        // 这个函数的参数可能不会被使用
        //... 一些代码 ...
    }
    
    [[maybe_unused]] int unusedVariable = 10; // 这个变量可能不会被使用
    
  4. [[deprecated]]Property example:

    [[deprecated("Use newFunction() instead")]]
    void oldFunction() {
          
          
        //... 一些代码 ...
    }
    
    void newFunction() {
          
          
        //... 一些代码 ...
    }
    
    void example() {
          
          
        oldFunction(); // 调用此函数时,编译器会发出弃用警告
        newFunction(); // 正确的函数调用
    }
    

These examples show how to use these properties in C++ code. Remember, the main purpose of these attributes is to provide additional information to the compiler to help programmers write clearer and safer code.

3. Suitable scenarios

The applicable scenarios for each attribute are as follows:

  1. [[fallthrough]] Applicable scenarios for attributes:

    • IntentionalcasePenetration: In a switch statement, when you intentionally let a Used when the case block falls through into the next case block. This is common in some logic processing, such as sharing the same block of code across a series of conditions.
    • Improve code readability: Even if case penetration is logically allowed, not using [[fallthrough]] may result in Maintainers misunderstand code intent. Using this attribute makes it clear that this is intentional and not a coding error.
  2. [[nodiscard]] Applicable scenarios for attributes:

    • Important return value: Used for functions whose return value is very important, such as error checking, status retrieval or calculation results. These return values ​​ignore the possibility of causing logic errors or resources. Give way.
    • API design: When designing a library or API, force callers to handle return values, especially for functions that may return error codes or statuses.
  3. [[maybe_unused]] Applicable scenarios for attributes:

    • Conditional compilation: When using conditional compilation in your code (such as using #ifdef), some variables or functions may only be used under specific conditions . Use [[maybe_unused]] to avoid warnings when these variables or functions are not used.
    • Framework or library code: When writing general-purpose code or libraries, some parameters may not always be used, but they still need to be declared in order to maintain the consistency of the interface.
  4. [[deprecated]] Applicable scenarios for attributes:

    • Code migration and upgrade: During the software development process, when a function or class is replaced by a new implementation, mark the old version as deprecated to guide developers to use it new version.
    • Backward Compatibility: While maintaining backward compatibility, developers are reminded that certain features may be removed or changed in future versions, and encourage them to migrate to Updated implementation.
    • Avoid using unsafe or obsolete code: Use the [[deprecated]] attribute to reduce the risk of code that is known to have problems or is no longer recommended. Use in new developments.

By using these properties in appropriate scenarios, you can improve the security, maintainability, and clarity of your code.

Conclusion

In our programming learning journey, understanding is an important step for us to move to a higher level. However, mastering new skills and ideas always requires time and persistence. From a psychological point of view, learning is often accompanied by constant trial and error and adjustment, which is like our brain gradually optimizing its "algorithm" for solving problems.

This is why when we encounter mistakes, we should view them as opportunities to learn and improve, not just as annoyances. By understanding and solving these problems, we can not only fix the current code, but also improve our programming skills and prevent making the same mistakes in future projects.

I encourage everyone to actively participate and continuously improve their programming skills. Whether you are a beginner or an experienced developer, I hope my blog will be helpful on your learning journey. If you find this article useful, you may wish to click to bookmark it, or leave your comments to share your insights and experiences. You are also welcome to make suggestions and questions about the content of my blog. Every like, comment, share and attention is the greatest support for me and the motivation for me to continue sharing and creating.


Read my CSDN homepage and unlock more exciting content:Bubble CSDN homepage
Insert image description here

Guess you like

Origin blog.csdn.net/qq_21438461/article/details/135040323