简体   繁体   English

使用const引用别名化变量

[英]Aliasing a variable using const reference

When dealing with T instances obtained from an array or trough any other longish syntax, I often use a const T& to alias the object and make my code more readable (of course only if the lifetime of the object allows it). 当处理从数组或通过其他冗长语法获得的T实例时,我经常使用const T&为对象命名,并使我的代码更具可读性(当然,只有在对象的生存期允许时)。 I've seen this elsewhere, eg here on Stefan Reinalter's excellent blog. 我已经看到了这个在其他地方,比如这里对斯特凡Reinalter的优秀博客。 Stripped down and commented version of his code: 精简并注释了他的代码版本:

void Render()
{
    for (size_t i = 0; i < m_visibleSubMeshes.size(); ++i)
    {
        // Get current submesh from array and create alias
        const SubMesh& sm = m_subMeshes[i];

        // Enjoy shortened syntax using the const reference
        context->Draw(sm.startIndex, sm.numIndices);
    }
}

Does this ever result in additional instructions, or will this under all circumstances be the same as accessing m_subMeshes[i].startIndex and m_subMeshes[i].numIndices directly? 这是否会导致附加指令,还是在所有情况下都与直接访问m_subMeshes[i].startIndexm_subMeshes[i].numIndices

It depends on the configuration. 这取决于配置。

If optimizations are in place it should produce the same results for any good compiler. 如果进行了优化,那么对于任何好的编译器,它都应产生相同的结果。 This would be typical for release builds. 对于发行版本,这将是典型的。

If optimizations are disabled it should produce fewer instructions, since you are de-referencing the collection just one time. 如果禁用了优化,则应该产生较少的指令,因为您仅一次取消引用集合。 This would be typical for debug builds, in this case it could also have the advantage of easier object inspection. 这对于调试版本来说是很典型的,在这种情况下,它还具有易于检查对象的优点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM