在C ++中的头文件中编写函数定义 [英] Writing function definition in header files in C++

查看:543
本文介绍了在C ++中的头文件中编写函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有很多小的功能。通过小函数,我的意思是不做任何处理,但只是返回一个字面值的函数。像

I have a class which has many small functons. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like

string Foo::method() const{
    return "A";
}



我创建了一个头文件Foo.h和源文件Foo .cpp。但是由于函数非常小,我想把它放在头文件本身。我有以下问题

I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am thinking about putting it in the header file itself. I have the following questions


  1. 如果我把这些函数defnition放在头文件中,是否有任何性能或其他问题?我将有很多这样的功能。

  2. 我的理解是当编译完成后,编译器将展开头文件并将其放在它包含的位置。是否正确?


推荐答案

如果函数很小是低的),如果该函数可以放入标头,而不包括无数其他标头(因为你的功能取决于它们),这是完全有效的。如果你声明它们extern inline,那么编译器需要给每个编译单元相同的地址:

If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same address for every compilation unit:

headera.h

inline string method() {
    return something;
}


$ b <同样的东西对他们是真实的:如果他们可以放入标题没有麻烦,你可以这样做。

Member functions are implicit inline provided they are defined inside their class. The same stuff is true for them true: If they can be put into the header without hassle, you can indeed do so.

因为函数的代码放在标题中并可见,所以编译器能够内联调用它们,即将函数的代码直接放在调用网站(不是那么多,因为你放在内联之前,但更多的是因为编译器决定的方式,虽然,只是inline只是一个提示,编译器)。这可以导致性能提高,因为编译器现在可以看到参数匹配函数本地的变量,并且其中参数不会彼此别名 - 最后但并非最不重要的是,不再需要功能框架分配。

Because the code of the function is put into the header and visible, the compiler is able to inline calls to them, that is, putting code of the function directly at the call site (not so much because you put inline before it, but more because the compiler decides that way, though. Putting inline only is a hint to the compiler regarding that). That can result in a performance improvement, because the compiler now sees where arguments match variables local to the function, and where argument doesn't alias each other - and last but not least, function frame allocation isn't needed anymore.


我的理解是编译完成后,编译器会展开头文件并将其放在包含的位置。是否正确?

My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?

是的,这是正确的。该函数将在包含其标题的每个地方定义。编译器将关心将其中的一个实例放入结果程序中,通过删除其他实例。

Yes, that is correct. The function will be defined in every place where you include its header. The compiler will care about putting only one instance of it into the resulting program, by eliminating the others.

这篇关于在C ++中的头文件中编写函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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