gpt4 book ai didi

c++ - pimpl 中的方法是否内联?

转载 作者:太空狗 更新时间:2023-10-29 19:38:11 25 4
gpt4 key购买 nike

考虑下一个简单的例子:

标题:

// a.hpp
#ifndef A_HPP
#define A_HPP
#include <memory>

class A
{
public:
A();

int foo();

private:
struct Imp;
std::auto_ptr< Imp > pimpl;
};

#endif // A_HPP

实现:

// a.cpp
#include "a.hpp"

struct A::Imp
{
int foo()
{
// do something and return the result
}
};

A::A() : pimpl( new Imp )
{}
int A::foo()
{
return pimpl->foo();
}

主要内容:

// main.cpp
#include "header.hpp"
int main()
{
A a;
return a.foo();
}

问题是:
A::Imp::foo 方法是否要内联到 A::foo 中?
它是否取决于该方法中的实现?

附言我正在使用 gcc(如果重要的话是 4.3.0)。

编辑

我想我没有解释清楚。我的意思是这样的。如果我使用最大优化级别,//do something and return the result 将被放置在 A::foo()A 中: :Imp::foo()?
没有优化,我看到这没有完成(pimpl->foo() 仍然被调用)。

我知道 A::foo() 永远不会内联到 main() 中,但这不是我要问的。

最佳答案

Herb Sutter 曾经写过一篇关于内联的很棒的文章。

要问的第一个问题是:什么时候可以进行内联?

在 C++ 中:

  • 可能发生在编译阶段
  • 它可能发生在链接阶段(LTO:Link Time Optimization)

这两种机制都是相似的:如果编译器/链接器知道方法的实现,它可能会决定复制/粘贴实现而不是发出调用。这个决定是基于复杂的启发式方法,我只知道它们存在,不知道它们是关于什么的。

因此,关键点是了解实现位。

  • 对于编译器:意味着定义在同一个翻译单元
  • 对于链接器:这意味着在被链接的翻译单元之一中定义,或者在它将链接到的静态库中定义...据我所知,如果该方法驻留在 DLL 中,则不会对其进行优化

所以这里:是的,pimpl->foo() 调用可以内联在A::foo 中。这将取决于编译器编译选项。

对于 gcc/clang,如果 A::Impl::foo 足够小,它可以从 O1 开始优化(除非你通过 -fno-inline) .

关于c++ - pimpl 中的方法是否内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6251237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com