为什么 C++ 有时在类内部定义方法?

发布于 2024-07-07 17:52:56 字数 371 浏览 11 评论 0原文

我经常遇到 C++ 中的大型非模板类,其中简单方法直接在头文件的类主体中定义,而不是在实现文件中单独定义。 例如:

class Foo {
  int getBar() const { return bar; }
  ...
};

为什么要这样做? 看来缺点还是有的。 实现没有像应有的那样隐藏,代码的可读性较差,如果类的头文件包含在许多不同的地方,编译器的负担也会增加。

我的猜测是,人们希望将这些函数内联到其他模块中,这可以显着提高性能。 但是,我听说较新的编译器可以在跨模块的链接时进行内联(和其他过程间优化)。 对这种链接时优化的支持有多广泛?它实际上使这些定义变得不必要吗? 这些定义还有其他充分的理由吗?

I frequently run into large, non-template classes in C++ where simple methods are defined directly in the class body in the header file instead of separately in the implementation file. For example:

class Foo {
  int getBar() const { return bar; }
  ...
};

Why do this? It seems like there are disadvantages. The implementation is not as hidden as it should be, the code is less readable, and there would also be an increased burden on the compiler if the class's header file is included in many different places.

My guess is that people intend for these functions to be inlined in other modules, which could improve performance significantly. However, I've heard newer compilers can do inlining (and other interprocedural optimizations) at link-time across modules. How broad is the support for this kind of link-time optimization, and does it actually make these kind of definitions unnecessary? Are there any other good reasons for these definitions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆萌少年 2024-07-14 17:52:56

C++ 标准规定,类定义中定义的方法默认是内联。 这会显着提高简单函数(例如 getter 和 setter)的性能。 链接时跨模块优化比较困难,尽管某些编译器可以做到这一点。

The C++ standard says that methods defined inside the class definition are inline by default. This results in obvious performance gains for simplistic functions such as getters and setters. Link-time cross-module optimization is harder, although some compilers can do it.

合久必婚 2024-07-14 17:52:56

通常没有其他原因,只是更容易并且节省时间。 它还可以在实现文件中节省一些混乱,同时在头文件中占用相同数量的行。 如果仅限于诸如 getter 和 setter 之类的东西,那么可读性较差是相当困难的。

Often there's no reason other than it's just easier and saves time. It also saves a little clutter in the implementation file, while taking up the same number of lines in the header file. And being less readable is quite a stretch if it's limited to things like getters and setters.

怎会甘心 2024-07-14 17:52:56

您回答了自己的问题,它们确实是内联方法。

使用它们的原因是性能。

You answered your own question, they are indeed inline methods.

Reasons to use them are performance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文