为什么两个函数有相同的地址?
考虑这个函数模板:
template<typename T>
unsigned long f(void *) { return 0;}
现在,我将 f
和 f
的地址打印为:
std::cout << (void*)f<A> << std::endl;
std::cout << (void*)f<B> << std::endl;
如果在 MSVS10 中编译,为什么它们会打印相同的地址?它们不是两个不同的函数,因此应该打印不同的地址吗?
更新:
我意识到在 ideone 上,它打印了不同的地址。 MSVS10 优化了代码,因为该函数不以任何方式依赖于 T
,因此它会生成相同的函数。 @Mark 对此的回答和评论很有价值。 :-)
Consider this function template:
template<typename T>
unsigned long f(void *) { return 0;}
Now, I print the addresses of f<A>
and f<B>
as:
std::cout << (void*)f<A> << std::endl;
std::cout << (void*)f<B> << std::endl;
Why do they print the same address if compiled in MSVS10? Are they not two different functions and therefore should print different addresses?
Updated:
I realized that on ideone, it prints the different address. MSVS10 optimizes the code, as the function doesn't depend on T
in any way, so it produces same function. @Mark's answer and comments on this are valuable. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要转换为
void *
:如果您转换为函数指针(或其他几个类的非 void 指针),它将被解释为
bool
std::ostream
的运算符<<
(因此是1
)。You need to cast to
void *
:If you cast to a function pointer (or several other classes of non-void pointers), it will be interpreted as a
bool
by theoperator<<
forstd::ostream
(hence the1
).由于该函数不依赖于模板参数,因此编译器可以将所有实例化压缩为单个函数。
我不知道为什么您会得到
1
地址。由 Nawaz 添加:
我用我的真实代码进行了实验,并得出结论,@Mark 上面所说的在这里非常重要:
由于函数不依赖于模板参数,因此编译器可以将所有实例化压缩为单个函数。
我还得出一个结论,如果函数体依赖于
T*
,不上T
,它仍然在我的真实代码中为不同类型的参数生成相同的函数(尽管不是在 ideone 上)。但是,如果它依赖于 T,那么它会产生不同的函数,因为对于不同类型的参数,sizeof(T) 是不同的(对我来说幸运的是)。所以我在函数模板中添加了一个
T
类型的虚拟自动变量,这样函数就可以依赖于T
的大小,从而迫使它产生不同的功能。Since the function doesn't depend on the template parameter, the compiler can condense all instantiations into a single function.
I don't know why you get
1
for the address.Added by Nawaz:
I experimented with my real code, and concluded that what @Mark said above is very important here :
Since the function doesn't depend on the template parameter, the compiler can condense all instantiations into a single function.
I also came to a conclusion that if the function-body depends on
T*
, not onT
, it still produces the same function for different type arguments in my real code (not on ideone, though). However, if it depends onT
, then it produces different functions, becausesizeof(T)
differs (fortunately for me) for different type arguments.So I added a dummy automatic variable of type
T
in the function template, so that the function could depend on the size ofT
so as to force it to produce different functions.这只是未定义行为的一种情况,因为将函数指针转换为对象类型指针的结果是未定义的。
要检查的更有趣的表达式是
f == f
当且仅当A
和B
引用相同类型时,其计算结果应为true
。This is simply a case of undefined behavior because the results of casting a pointer to a function to a pointer to object type are undefined.
A more interesting expression to examine would be
f<A> == f<B>
which should evaluate totrue
if and only ifA
andB
refer to the same type.