为什么函数指针都具有相同的值? [英] Why do function pointers all have the same value?

查看:73
本文介绍了为什么函数指针都具有相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

using namespace std;
#include <iostream>

void funcOne() {
}

void funcTwo( int x ) {
}

int main() {

  void (*ptrOne)() = funcOne;
  cout << ptrOne << endl;      //prints 1

  void (*ptrTwo)( int x ) = funcTwo;
  cout << ptrTwo << endl;      //prints 1

  int (*ptrMain)() = main;
  cout << ptrMain << endl;     //prints 1

}

有人知道背后的原因吗?起初我以为是因为我从不调用这些函数,所以这些函数不存在于内存中,因此它们也从未添加到堆栈中.但是,即使指向主函数的指针的值也会打印出1.

Does anyone know the reasoning behind this? At first I thought it was because the functions don't exist in memory since I never call on them, and thus they never get added to the stack. But even the value of a pointer to the main function prints out 1.

推荐答案

函数指针不会隐式转换为void *,这是operator <<重载的原因.

Function pointers do not implicitly convert to void *, which is what operator << overloads on.

这是在C ++ 11§4.10/2中通过省略指定的:

This is specified by omission in C++11 §4.10/2:

指向cv T的指针"类型的prvalue,其中T是对象类型,可以转换为指向cv T的指针"的prvalue.将"pointer to cv T"转换为"pointer to cv void"的结果指向类型T的对象所在的存储位置的开始,就好像该对象是类型T的最派生对象(1.8)一样. (即不是基类的子对象).空指针值将转换为目标类型的空指针值.

A prvalue of type "pointer to cv T," where T is an object type, can be converted to a prvalue of type "pointer to cv void". The result of converting a "pointer to cv T" to a "pointer to cv void" points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject). The null pointer value is converted to the null pointer value of the destination type.

函数类型不是对象类型.

Function types are not object types.

此外,您甚至无法使用static_cast来做到这一点.函数和对象可能生活在完全不同的地址空间(这称为哈佛体系结构)中,并且指针大小不同.可以使用reinterpret_cast 来将函数指针转换为void *:它是有条件支持的"(C ++ 11§5.2.10/8).这样的void *仅应用于打印或转换回原始函数指针类型.

Moreover, you can't even do it using static_cast. Functions and objects may live in completely different address spaces (this is called Harvard architecture), with differently-sized pointers. Converting a function pointer to void * can maybe be done with reinterpret_cast: it's "conditionally-supported" (C++11 §5.2.10/8). Such a void * should only be used for printing or conversion back to the original function pointer type.

这篇关于为什么函数指针都具有相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆