DEV Community

Cover image for 用 cout 顯示函式的位址
codemee
codemee

Posted on

1

用 cout 顯示函式的位址

前幾天在探究虛擬函式的時候, 想要把函式的位址顯示出來, 於是就遇到了靈異現象, 以底下的程式碼為例:

#include <iostream>

using namespace std;

void foo() {
    cout << "foo()" << endl;
}

int main(void)
{
    cout << foo << endl;
}   
Enter fullscreen mode Exit fullscreen mode

卻得到以下的輸出:

1
Enter fullscreen mode Exit fullscreen mode

研究了一下才發現, 雖然 cout 所屬的類別 std::basic_ostream 有以下的 << 運算子多載版本:

basic_ostream& operator<<( const void* value );
basic_ostream& operator<<( const volatile void* value );
Enter fullscreen mode Exit fullscreen mode

不過指向特定型別的指位器並不能自動轉型成 (void*), 但是卻可以自動轉型到 bool, 因此編譯器會選用以下這個版本

basic_ostream& operator<<( bool value );
Enter fullscreen mode Exit fullscreen mode

它會用 1 和 0 表示 truefalse, 所以不是指向 null 的指位器就被轉成 true, 印出 1 了。

如果要印出位址, 就必須先手動把指位器轉型成 (void*), 像是這樣:

#include <iostream>

using namespace std;

void foo() {
    cout << "foo()" << endl;
}

int main(void)
{
    cout << (void*)foo << endl;
}   
Enter fullscreen mode Exit fullscreen mode

才會印出位址:

0x7ff78d461540
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs