私の知る限り、ポインターは変更できるがデータは変更できないconst int *
ことを意味しint * const
、ポインターアドレスは変更できないがデータは変更できると言いconst int * const
、それらのいずれも変更できないと述べています。
ただし、 type で定義されたポインターのアドレスを変更することはできませんconst int *
。これが私のコード例です:
void Func(const int * pInt)
{
static int Int = 0;
pInt = ∬
Int++;
}
int wmain(int argc, wchar_t *argv[])
{
int Dummy = 0;
const int * pInt = &Dummy;
//const int * pInt = nullptr; // Gives error when I try to pass it to Func().
std::cout << pInt << '\t' << *pInt << std::endl;
std::cout << "-------------------" << std::endl;
for (int i=0; i<5; i++)
{
Func(pInt); // Set the pointer to the internal variable. (But, it doesn't set it!)
std::cout << pInt << '\t' << *pInt << std::endl;
}
return 0;
}
コード出力:
00D2F9C4 0
-------------------
00D2F9C4 0
00D2F9C4 0
00D2F9C4 0
00D2F9C4 0
00D2F9C4 0
少なくとも 1 回呼び出した後、のアドレスが関数pInt
内の内部変数を指すように変更されることを期待します。しかし、そうではありません。変数を指し続けます。Func()
Func()
Dummy
ここで何が起きてるの?期待した結果が得られないのはなぜですか?
(IDE: Visual Studio 2015 コミュニティ バージョン)