What Happens When We Lie to the Compiler?
Posted on November 13th, 2009 at 12:57 by fr3@K
When you lie to your compiler, don’t be surprised to get results those differ from what you expect.
In this case, the coder promised his/her compiler the value of “value” won’t be changed, as it was declared const.
Therefore our best friend (yes, the compiler) who trusted the coder, thought “hey, I could cache this value in a register and not fetch it from RAM every time I reference it”, i.e. optimization.
If we change the code in the link slightly, so that function funcC would print *value before the assignment, one would see that the value of *value had actually been modified by function funcA. However, the modification was not visible in main, because the compiler was lied to as the coder explicitly told it that there would be no modification to value.
In the body of function funcC, though value was declared as a pointer to const instance, the compiler was smart enough to know it was lied to. There was a const_cast and a assignment, therefore, the modification to *value was reflected in the output.
Observer Pattern, Done Differently
Posted on May 24th, 2009 at 20:43 by fr3@K
In a recent post of Scott Wheeler’s – C and C++ are not the same language. He talked about differences between C and C++, and applications of different programming languages (C, C++, Java, Ruby) in his company.
In the post, Wheeler implemented observer pattern in C, C++ and Java, demonstrating some of his points – including how C and C++ are different from each other, and how C++ and Java are actually more alike.
Though I do agree with Wheeler’s conclusion for the most part, I failed to share his view in C, C++ and Java comparison. IMHO, his observer implementation in C++ is rather old school, or should I say it’s so Java.
(more…)
Re: G++ 尚未支援 extern template?
Posted on December 8th, 2008 at 0:40 by fr3@K
回應 G++ 尚未支援 extern template? 原文作者的意見:
原來如此,不過的確 header file 跟 implementation file 有時是有分開的必要,那麼,對 function template 來說又該怎麼作比較好?
先認錯一下, 我在該文的回應中數次提到 extern template. 事後我又研究了一下, 是我搞錯了, 應該是 exported template.
兩者為相關但功能不同的 C++ feature.
我的錯誤導致作者把文章的標題改錯了, sorry… 我的回應應更正為:
即便已編譯成 library, 當 library source 內有 extern template exported template 時, client code 依然需要該 extern template template definition 的 source code 才能 link 到 template 的 instance.
Note: gcc 4.3/4.4 的確支援 extern templates.
(more…)