★const_cast★


最後はconst_castについて説明します。


const_cast


最後はconst_castです。

これも非常に特殊なキャストで、constを外せるというキャストです。

<sample program cpp046-01>

#include <iostream>

void ShowValue(const int &refValue);

int main()
{
    int value = 23;

    ShowValue(value);

    return 0;
}

void ShowValue(const int &refValue)
{
    std::cout << refValue << std::endl;
}

<実行結果>

23
続行するには何かキーを押してください・・・

関数ShowValueはconst参照を受け取る関数です。

当然、関数内で引数の書き換えは出来ません。

<sample program cpp046-02>

#include <iostream>

void ShowValue(const int &refValue);

int main()
{
    int value = 23;

    ShowValue(value);

    return 0;
}

void ShowValue(const int &refValue)
{
    std::cout << refValue << std::endl;

    refValue = 21;
}

<コンパイル結果>

error C3892: 'refValue': const である変数へは割り当てることはできません

ダメですね。

では、これはどうでしょうか?

<sample program cpp046-03>

#include <iostream>

void ShowValue(const int &refValue);

int main()
{
    int value = 23;

    ShowValue(value);

    return 0;
}

void ShowValue(const int &refValue)
{
    std::cout << refValue << std::endl;

    int &ref = refValue;
}

<コンパイル結果>

error C2440: '初期化中': 'const int' から 'int &' に変換できません。
note: 変換で修飾子が失われます。

参照refValueの「別名」を「int &ref」に変えようとしました。

constが付いていない型なので、この変換が出来てしまうと元データのvalueを書き換える事が出来るようになってしまいます。

当然、これもダメです。

しかし、const_castを使うと・・・

<sample program cpp046-04>

#include <iostream>

void ShowValue(const int &refValue);

int main()
{
    int value = 23;

    ShowValue(value);

    return 0;
}

void ShowValue(const int &refValue)
{
    std::cout << refValue << std::endl;

    int &ref = const_cast<int&>(refValue);
}

<実行結果>

23
続行するには何かキーを押してください・・・

エラーが消えました。

では、ref経由でvalueを書き換えられるかどうか試します。

<sample program cpp046-05>

#include <iostream>

void ShowValue(const int &refValue);

int main()
{
    int value = 23;

    ShowValue(value);

    ShowValue(value);

    return 0;
}

void ShowValue(const int &refValue)
{
    std::cout << refValue << std::endl;

    int &ref = const_cast<int&>(refValue);

    ref = 12;
}

<実行結果>

23
12
続行するには何かキーを押してください・・・

書き換えられています・・・


このキャストも危険なキャストです。

普通にプログラムを作っていれば使うところはありませんので、訳の分からないところで使わないようにしてください。


次へ

戻る

目次へ