Can const-correctness improve performance?

前端 未结 4 522
清歌不尽
清歌不尽 2020-11-29 18:22

I have read numerous times that enforcing const-correctness in your C or C++ code is not only a good practice with regards to maintainability, but also it may allow your com

4条回答
  •  囚心锁ツ
    2020-11-29 18:45

    const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic, meaning the compiler has to respect changes made by other threads.

    That said, it is trivial for the compiler to look at the code it generates and determine if it actually writes to a given variable, and apply optimizations accordingly.

    That all said, const correctness is a good thing with respect to maintainability. Otherwise, clients of your class could break that class's internal members. For instance, consider the standard std::string::c_str() -- if it couldn't return a const value, you'd be able to screw around with the internal buffer of the string!

    Don't use const for performance reasons. Use it for maintainability reasons.

提交回复
热议问题