Why is const-correctness specific to C++?

后端 未结 14 596
盖世英雄少女心
盖世英雄少女心 2020-12-23 16:42

Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as oppos

14条回答
  •  悲哀的现实
    2020-12-23 16:58

    In C, Java and C# you can tell by looking at the call site if a passed object can be modified by a function:

    • in Java you know it definitely can be.
    • in C you know it only can be if there is a '&', or equivalent.
    • in c# you need to say 'ref' at the call site too.

    In C++ in general you can't tell this, as a non-const reference call looks identical to pass-by-value. Having const references allows you to set up and enforce the C convention.

    This can make a fairly major difference in readability of any code that calls functions. Which is probably enough to justify a language feature.

提交回复
热议问题