“void function()"和“void function()"有什么区别?和“void *function()"? [英] What is the difference between "void function()" and "void *function()"?
问题描述
我知道 void *function()
是指向函数的指针,但我不知道它们的工作方式以及何时使用 void *function()
代码>?我在组装方面做了一些研究,以比较它们在幕后的工作方式以及它们看起来是一样的.这是 C++ 代码:
I knew the void *function()
is the pointer which point to a function but I don't know how different they work and when we use void *function()
?
I did some research in assembly to compare how they work behind the scene and look like they are same.
Here is the c++ code:
void *bar(){
std::cout << "bar" << std::endl;
}
void foo(){
std::cout << "foo" << std::endl;
}
int main(void){
foo();
bar();
return 0;
}
这是我从 objdump 收到的汇编指令
And this is assembly instruction I receive from objdump
void *bar(){
400846: 55 push %rbp
400847: 48 89 e5 mov %rsp,%rbp
std::cout << "bar" << std::endl;
40084a: be 84 09 40 00 mov $0x400984,%esi
40084f: bf 60 10 60 00 mov $0x601060,%edi
400854: e8 b7 fe ff ff callq 400710 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>
400859: be 30 07 40 00 mov $0x400730,%esi
40085e: 48 89 c7 mov %rax,%rdi
400861: e8 ba fe ff ff callq 400720 <_ZNSolsEPFRSoS_E@plt>
}
400866: 90 nop
400867: 5d pop %rbp
400868: c3 retq
0000000000400869 <_Z3foov>:
void foo(){
400869: 55 push %rbp
40086a: 48 89 e5 mov %rsp,%rbp
std::cout << "foo" << std::endl;
40086d: be 88 09 40 00 mov $0x400988,%esi
400872: bf 60 10 60 00 mov $0x601060,%edi
400877: e8 94 fe ff ff callq 400710 <_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt>
40087c: be 30 07 40 00 mov $0x400730,%esi
400881: 48 89 c7 mov %rax,%rdi
400884: e8 97 fe ff ff callq 400720 <_ZNSolsEPFRSoS_E@plt>
}
400889: 90 nop
40088a: 5d pop %rbp
40088b: c3 retq
000000000040088c <main>:
int main(void){
40088c: 55 push %rbp
40088d: 48 89 e5 mov %rsp,%rbp
foo();
400890: e8 d4 ff ff ff callq 400869 <_Z3foov>
bar();
400895: e8 ac ff ff ff callq 400846 <_Z3barv>
return 0;
40089a: b8 00 00 00 00 mov $0x0,%eax
}
40089f: 5d pop %rbp
4008a0: c3 retq
推荐答案
重复你在评论中的答案,区别在于返回的类型
To repeat the answers you had in the comments already, the difference is the type returned
void foo() { ... }
是一个什么都不返回的函数,而
Is a function that returns nothing, while
void *bar() { ... }
void* bar() { ... } // Identical
返回一个 void
指针.在 *
之前或之后交换空格位置在这里没有区别,但它可能会使返回类型更清楚.当然,在这个 bar
函数的情况下,当然要确保实际返回一些东西,否则你至少会收到编译器警告和未定义的行为.
Return a void
pointer. Swapping the space position before or after the *
makes no difference here, but it may make it clearer what the return type is. And of course make sure to actually return something in the case of this bar
function, or you will have a compiler warning at least, and undefined behavior.
所以基本上这只是要记住的关键字 void
的两个略有不同的含义.如果您不熟悉 C++,这里有大量可访问的书籍也可以帮助您.
So basically this is just two slightly different meanings of the keyword void
to remember. If you are not familiar with C++ there a good amount of accessible book that can help you too.
这篇关于“void function()"和“void function()"有什么区别?和“void *function()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!