我有一个定义函数 run
的类的以下示例,该函数依赖于对虚函数 get_vars
的调用(我正在考虑行 for (auto int_vars_it : get_vars()) ...
).
我的问题是:我的示例的性能是否会因为我在 for
循环的上限调用 get_vars()
而变慢?我担心循环的每个实例都会调用该函数,如果循环运行多次,这可能会降低性能。
#include <iostream>
class Bas
{
protected:
using vars_type = std::vector<std::string>;
private:
vars_type vars_Base;
protected:
virtual vars_type &get_vars()
{
return vars_Base;
}
public:
void push_back(const std::string &str)
{
get_vars().push_back(str);
}
void run()
{
for (auto int_vars_it : get_vars())
{
std::cout << int_vars_it << " ";
}
}
};
int main()
{
Bas b;
b.push_back("aB");
b.run();
return 0;
}
最佳答案
它只会被调用一次并返回对 std::vector
的引用。之后,它将迭代 vector 的内容,这些内容将在某个时候被翻译成经典的 for
循环。
关于c++ - 虚拟函数调用的性能作为for循环中的上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45772806/