将此布尔值传递给此函数的最有效方法是什么?

what is the most efficient way to pass in this bool to this function?

本文关键字:有效 方法 是什么 函数 布尔 值传      更新时间:2023-10-16

我在另一个类中有一个函数,它将每帧调用一次,我想知道传递此布尔值的最佳方法。最好的方法是什么?我有两个选择,我不确定最好的选择是什么?或者是否有更好的方法来完全做到这一点?有问题的布尔值是"减少布尔值">

选项 1:

Class 1:
void Update()
{
SkillSelectionArrow skillArrow
skillArrow.Update(deltaTime, &skills.weight, true);
}
Class 2:
void SkillSelectionArrow::Update(float * deltaTime, int *valueToBeChanged, bool decrease)
{
if (this->CheckSpecificCollision(mouse) && input->getMouseLeftDown() == true)
{
decrease == true ? valueToBeChanged++ : valueToBeChanged--;     
}
}

或者初始化布尔值会更有效并传递它,例如:

选项 2:

Class 1:
void Update()
{
SkillSelectionArrow skillArrow
bool decrease = true;
skillArrow.Update(deltaTime, &skills.weight, &decrease);
}
Class 2:
void SkillSelectionArrow::Update(float * deltaTime, int *valueToBeChanged, bool *decrease)
{
if (this->CheckSpecificCollision(mouse) && input->getMouseLeftDown() == true)
{
*decrease == true ? valueToBeChanged++ : valueToBeChanged--;        
}
}

谢谢

按值传递通常更适合小对象。指针可能大于对象本身。

一般规则是,如果对象的大小小于2*sizeof(void*),则按值传递。(见 https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-in(

因此,floatint通常是按值传递的(除非你想在函数中修改它们!

请注意,性能影响可能非常小,可能可以忽略不计。更重要的是能够理解方法的意图。当你通过指针时,看起来好像你想修改对象,但对于布尔值,你不想这样做,对吧?