知秋一叶

日出而作,日入而息,凿井而饮,耕田而食,帝力何有于我哉
随笔 - 55, 评论 - 311, 引用 - 79

导航

工具

标签

每月存档

广告



访客

 

  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.

 

 

相关文章

Loading...

打印 | 张贴于 2004-09-19 09:29:00 | Tag:.NET

留言反馈

#re:C# Const Correctness 编辑
C# Const Correctnessooeess
2005-06-14 10:27:00 | [匿名用户:测汞]
#re:C# Const Correctness 编辑
^_~,pretty good!csharpsseeoo
2005-05-16 17:02:00 | [匿名用户:工业pH计]
#re:C# Const Correctness 编辑
^_^,Pretty Good!
2005-04-16 01:39:00 | [匿名用户:CO一氧化碳检测仪]
#re:C# Const Correctness 编辑
^_^,Pretty Good!
2005-04-10 19:56:00 | [匿名用户:CO一氧化碳检测仪]
#re: C# Const Correctness 编辑
这个东东好像Fortran.NET实现了,在那里面叫Pure Function
2004-09-20 08:09:00 | [匿名用户:Ninputer]
#re: C# Const Correctness 编辑
最近我也在思考这个const的事情。从很多方面都可以看出C#和C++设计完全出于两个出发点的。

至于.net generics,事实完全可以做得更好,stan lippman在他的blog里不无怨言的说如果设计.net generic时,有他参与的话,可能出来的东西就会很不一样。

知秋一叶有在研究C++/CLI方面的东西吗?似乎stan lippman目前在做的很多工作都很吸引人。
2004-09-19 23:08:00 | [匿名用户:Justin Shen]
对不起,目前本随笔不允许发表新评论.

Powered by: Joycode MVC Blogger System