A question pops up from the forum regarding the const correctness in C++: “Why don't we have it in C#?”
In C++, if a method is declared like this:
class MyClass {
void foo() const;
};
It implies that the author claims that the method won't change any internal data of MyClass object. It's a very handy way to allow compiler to check the semantics of your program. In C#, however, we don't have any corresponding constructs. An explanation from Anders Hejlsberg can be found here (Check out the immutable section).
My understanding of the problem is that C++ is a designed to be flexible: most of the things are optional. Even inside a const function, for example, you still have the option of using const_cast to strip the const and get a mutable version. C#, on the other hand, is designed to have unified and strong semantics: If you ever have the keyword “const“ in C#, there is a good chance that you won't be able to cast it away.
Const correctness is a very nice feature to have. But like checked exceptions, once enforced strictly by the language and runtime, it will make your life miserable. For example, once you get a const reference, you CAN'T call any member method that is not marked const. Even worse, the reference to a member variable will be const too. If the class library is not designed extremely careful, this chain react will eventually make you wish the const constraint were never there.
打印 | 张贴于 2004-09-19 09:29:00 | Tag:.NET
留言反馈
至于.net generics,事实完全可以做得更好,stan lippman在他的blog里不无怨言的说如果设计.net generic时,有他参与的话,可能出来的东西就会很不一样。
知秋一叶有在研究C++/CLI方面的东西吗?似乎stan lippman目前在做的很多工作都很吸引人。