为什么两个函数具有相同的地址? [英] Why do two functions have the same address?

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

问题描述

考虑此函数模板:

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中编译时打印相同的地址?它们不是两个不同的功能,因此应该打印不同的地址?

Why do they print the same address if compiled in MSVS10? Are they not two different functions and therefore should print different addresses?

更新:

我意识到在ideone上, 。 MSVS10优化代码,因为函数不以任何方式依赖于 T ,因此它产生相同的函数。 @ Mark的回答和对此的评论是有价值的。 : - )

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. :-)

推荐答案

由于函数不依赖于模板参数,编译器可以将所有实例化为单个函数。

Since the function doesn't depend on the template parameter, the compiler can condense all instantiations into a single function.

我不知道为什么你会得到 1 的地址。

I don't know why you get 1 for the address.

我试验了我的实际代码,并得出结论,@Mark上面说的是非常重要的:

I experimented with my real code, and concluded that what @Mark said above is very important here :

该函数不依赖于模板参数,编译器可以将所有实例化为单个函数。

我也得出结论,如果函数体依赖于 T * ,而不是 T ,它仍然为我的不同类型参数产生相同的函数真正的代码(不在ideone,虽然)。但是,如果它依赖于 T ,那么它会产生不同的函数,因为 sizeof(T)

I also came to a conclusion that if the function-body depends on T*, not on T, it still produces the same function for different type arguments in my real code (not on ideone, though). However, if it depends on T, then it produces different functions, because sizeof(T) differs (fortunately for me) for different type arguments.

所以我添加了一个 T c类型的自动变量>在函数模板中,以便函数可以依赖于 T 的大小,以便强制它产生不同的函数。

So I added a dummy automatic variable of type T in the function template, so that the function could depend on the size of T so as to force it to produce different functions.

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

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