当前位置:首页 / 文章测试 / c++ core

c++ core

开始打字练习

Figure 3.1. Cippi assembles components

An interface is a contract between a service provider and a service user. Interfaces are according to the C++ Core Guidelines "probably the most important single aspect of code organization". The section on interfaces has about twenty rules. Four of the rules are related to contracts, which didn't make it in the C++20 standard.

A few rules related to interfaces use contracts, which may be part of C++23. A contract specifies preconditions, postconditions, and invariants for functions, that can be checked at run-time. Due to the uncertainty of the future, I ignore these rules. The appendix provides a short introduction to contracts.

Let me end this introduction with my favorite quote from Scott Meyers:

Make interfaces easy to use correctly and hard to use incorrectly.

-Scott Meyers

I.2: Avoid non-const global variables

Of course, you should avoid non-const global variables. But why? Why is a global variable, in particular when it is non-constant, bad? A global injects a hidden dependency into the function, which is not part of the interface. The following code snippet makes my point:

int glob{2011};

int mutiply(int fac) {

glob *= glob;

return glob * fac;

}

The execution of the function multiply changes, as a side-effect, the value of the global variable glob. Therefore, you can not test the function or reason about the function in isolation. When more threads use multiply concurrently, you have to protect the variable glob. There are more drawbacks to non-const global variables. If the function multiply had no side-effects, you could have stored the previous result and reuse the cached value for performance reasons.

The curse of non-const global variables

声明:以上文章均为用户自行发布,仅供打字交流使用,不代表本站观点,本站不承担任何法律责任,特此声明!如果有侵犯到您的权利,请及时联系我们删除。