相关疑难解决方法(0)

内联虚拟功能真的没有意义吗?

当我收到代码评论评论说虚拟功能不需要内联时,我收到了这个问题.

我认为在直接在对象上调用函数的场景中,内联虚函数可以派上用场.但是我想到的反驳论点是 - 为什么要想定义虚拟然后使用对象来调用方法呢?

最好不要使用内联虚拟功能,因为它们几乎从未扩展过吗?

我用于分析的代码片段:

class Temp
{
public:

    virtual ~Temp()
    {
    }
    virtual void myVirtualFunction() const
    {
        cout<<"Temp::myVirtualFunction"<<endl;
    }

};

class TempDerived : public Temp
{
public:

    void myVirtualFunction() const
    {
        cout<<"TempDerived::myVirtualFunction"<<endl;
    }

};

int main(void) 
{
    TempDerived aDerivedObj;
    //Compiler thinks it's safe to expand the virtual functions
    aDerivedObj.myVirtualFunction();

    //type of object Temp points to is always known;
    //does compiler still expand virtual functions?
    //I doubt compiler would be this much intelligent!
    Temp* pTemp = &aDerivedObj;
    pTemp->myVirtualFunction();

    return …
Run Code Online (Sandbox Code Playgroud)

c++ virtual-functions inline

167
推荐指数
5
解决办法
7万
查看次数

内联虚函数

在C++中,我的理解是可以内联虚函数,但通常会忽略内联提示.似乎内联虚函数没有太多意义.

是对的吗?

任何人都可以提供一个内联虚函数好的案例吗?

c++

20
推荐指数
2
解决办法
2万
查看次数

为什么虚拟成员函数会影响实际上不需要虚拟调度的 TU 的编译代码?

在这样的 TU 中

\n
#include "Foo.hpp"\nint main() {\n    // stuff\n    Foo* foo{new Foo{}};\n    foo->foo();\n    // stuff\n}\n
Run Code Online (Sandbox Code Playgroud)\n

其中Foo.hpp包含

\n
#pragma once\nstruct Foo {\n    virtual void foo(); // implmented somewhere\n};\n
Run Code Online (Sandbox Code Playgroud)\n

除了调用之外不会Foo::foo发生任何事情,对吗?fooisvirtual并且 it 也不是类 are final,所以是的,在另一个TU 中可能存在派生类的对象,等等,但是......就这个 TU 而言,我认为调用override foo是非常清楚的。我不明白事情会怎样。foo->foo()Foo::foo()

\n

那为什么生成的程序集是这样的呢?

\n
main:                                   # @main\n        push    rax\n        mov     edi, 8\n        call    operator new(unsigned long)@PLT\n        mov     rcx, qword ptr [rip + vtable for Foo@GOTPCREL]\n        add     rcx, …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance virtual-functions dynamic-dispatch virtual-table

2
推荐指数
1
解决办法
84
查看次数