gpt4 book ai didi

c++ - 从多态基指针调用基类方法很慢

转载 作者:行者123 更新时间:2023-11-28 00:00:15 26 4
gpt4 key购买 nike

标题很困惑..这是一个总结它的最小代码 -

#include <iostream>
#include <chrono>
#include <memory>

using namespace std;
using namespace std::chrono;

enum class TYPE {base, child};

class Base {
int n;
protected: Base(int _n) : n(_n) {}
public: virtual TYPE getType(){ return TYPE::base; }
};

class Child: public Base {
int m;
public:
TYPE getType(){ return TYPE::child; }
Child(int _n, int _m) : Base(_n), m(_m) {}
};

int main() {
unique_ptr<Base> b = make_unique<Child>(6, 7);
TYPE tB = TYPE::base;
TYPE tC = TYPE::child;

{
auto t1 = high_resolution_clock::now();

std::cout << (tB == b->Base::getType()) << ", ";

auto t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << "Duration: " << duration << std::endl;

}

{
auto t1 = high_resolution_clock::now();

std::cout << (tC == b->getType()) << ", ";

auto t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << "Duration: " << duration << std::endl;

}

return 0;
}

输出如下-

1, Duration: 12  // first run was 62
1, Duration: 0

我理解虚函数与普通(编译时间解析)函数相比可能会慢一点,但为什么上面的函数 - b->Base::getType() 比虚函数慢方法 - b->getType()?它是否进行了两次旅行,例如虚拟地解析函数然后返回到基类?谁能帮助我理解这一点?

IDEONE


嗯,稍微修改代码以包含循环,结果很清楚 -<强> IDEONE

1, Duration: 33
1, Duration: 1478051

最佳答案

调用 cout 所用的时间超过了单个函数调用的计时数字。最初的 cout 调用可能会为缓冲区分配内存,并且会花费更长的时间。

第一个调用 (b->Base::getType()) 不是虚拟的,甚至可以是内联的。

关于c++ - 从多态基指针调用基类方法很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652321/

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