null+****@clear*****
null+****@clear*****
2012年 4月 9日 (月) 15:06:56 JST
Kouhei Sutou 2012-04-09 15:06:56 +0900 (Mon, 09 Apr 2012)
New Revision: 613ff01b730e52843b40e44363e5a7f0a392569a
Log:
doc coding-style: add about cast
Modified files:
doc/source/developer/coding_style.rst
Modified: doc/source/developer/coding_style.rst (+39 -1)
===================================================================
--- doc/source/developer/coding_style.rst 2012-04-09 14:07:30 +0900 (e64473d)
+++ doc/source/developer/coding_style.rst 2012-04-09 15:06:56 +0900 (99fd6fe)
@@ -598,6 +598,45 @@ C++では真偽値に ``bool`` を使うためこのような状況は発生し
for (int i = 0; i < 10; ++i) {
}
+キャスト
+--------
+
+C++のスタイルを用いる
+^^^^^^^^^^^^^^^^^^^^^
+
+Cスタイルのキャストはなんでもキャストできてしまうため、意図しないキャストにも気付かない可能性がある。例えば、単に ``const`` を外したいだけなのに、間違って違う型に変換していても気付けない。C++のキャストでは ``const`` を外したいときは ``const_cast`` を使用し、型を変換するときは ``static_cast`` を指定する。こうすれば、 ``static_cast`` で間違って ``const`` を外してしまっている場合も気付ける。 ``reinterpret_cast`` はどうしても必要なときのみ注意して使う。
+
+よい例( ``const_cast`` を使っている):
+
+ uchar *to_key;
+ const ucahr *from_key;
+ KEY *key_info;
+ uint key_length;
+ key_copy(to_key, const_cast<uchar *>from_key, key_info, key_length);
+
+よい例( ``static_cast`` を使っている):
+
+ int n_hits = 1;
+ int n_documents = 10;
+ float hit_ratio = (float)(n_hits) / n_documents;
+
+よい例( ``static_cast`` では無理なので ``reinterpret_cast`` を使っている):
+
+ THD *thread = current_thd;
+ my_hash_delete(&mrn_allocated_thds, reinterpret_cast<uchar *>(thread));
+
+悪い例(Cスタイルのキャストを使っている):
+
+ int n_hits = 1;
+ int n_documents = 10;
+ float hit_ratio = (float)(n_hits) / n_documents;
+
+悪い例( ``static_cast`` で十分なのに ``reinterpret_cast`` を使っている):
+
+ void *value = get_value(key);
+ char *name;
+ name = reinterpret_cast<char *>(value);
+
その他
------
@@ -621,4 +660,3 @@ C++では真偽値に ``bool`` を使うためこのような状況は発生し
* typeidを使わない。
* 例外はMySQLで問題がないようであればOK。mroongaから外の世
界(MySQLの世界)にはださないようにする。
- * castはCのキャストではなくC++のキャストを使う。