将函数放在头文件中的经验法则 [英] Rules of thumb for putting functions in header files

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

问题描述

最近我开始把越来越​​多的函数到头文件,主要是为了方便。但我担心我可能会过度,我的标题是充满了包括,我不知道这是一个好主意。



你的经验法则是移动



如果你想知道,我在说的是开发应用程序,而不是开发库。



编辑:



我想如果我勾勒出内联(自然)




  • 更多清洁/

  • 无需更改任何Makefile即可链接到新文件。

  • 即时能够引入模板参数。



对比内联:




  • 增加编译时间(我不在乎这多少)

  • 很多包含在标题中(不应该这么大问题,如果他们使用卫兵)



根据这一点,似乎是一个好主意几乎把每个函数放在标题,相信这非常接近STL和Boost正在做的事情(尽管这些是库,而不是我的代码)。

解决方案

我最不可侵犯的规则之一:在头文件中只允许内联的函数体。其他任何东西都在链接阶段要求多个定义的麻烦。



标题应该主要用于声明,而不是定义。我有这个规则的例外(是灵活类型),但没有涉及非内联函数体。


Lately I have started to put more and more functions into header files, mostly for convenience. But I fear I might be overdoing it, my headers are full of includes and I'm not sure if that's a good idea.

What are your rules of thumb for moving functions out of or into header files?

In case you're wondering, I'm talking about developing applications, not libraries.

Edit:

I guess it's helpful if I outline the pros/cons of inline (naturally) header functions versus implementation functions from my point of view:

Pro inline:

  • More clean/concise.
  • No need for signature duplication.
  • No need to change any Makefile to link against new files.
  • Instant ability to introduce template parameters.

Contra inline:

  • Increased compile time (I don't care that much)
  • Many includes in headers (Shouldn't be such a big issue if they use guards)

According to that, it seems like a good idea to put pretty much every function in headers, and I believe that's pretty close to what the STL and Boost are doing (although those are libraries, as opposed to my code).

解决方案

One of my most inviolable rules: only function bodies which are inline are allowed in header files. Anything else is asking for trouble with multiple definitions in the link phase.

Headers should be left predominantly for declarations rather than definitions. I have exceptions to that rule (being the flexible type) but none of them involve non-inlined function bodies.

这篇关于将函数放在头文件中的经验法则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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