Navigation Menu

Skip to content

Commit

Permalink
doc coding-style: add about cast
Browse files Browse the repository at this point in the history
  • Loading branch information
kou committed Apr 9, 2012
1 parent a9730d9 commit 613ff01
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion doc/source/developer/coding_style.rst
Expand Up @@ -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);
その他
------

Expand All @@ -621,4 +660,3 @@ C++では真偽値に ``bool`` を使うためこのような状況は発生し
* typeidを使わない。
* 例外はMySQLで問題がないようであればOK。mroongaから外の世
界(MySQLの世界)にはださないようにする。
* castはCのキャストではなくC++のキャストを使う。

0 comments on commit 613ff01

Please sign in to comment.