现代C ++编译器是否可以避免在某些情况下两次调用const函数? [英] Are modern C++ compilers able to avoid calling a const function twice under some conditions?

查看:82
本文介绍了现代C ++编译器是否可以避免在某些情况下两次调用const函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有以下代码:

For instance, if I have this code:

class SomeDataProcessor
{
public:
    bool calc(const SomeData & d1, const SomeData & d2) const;
private:
    //Some non-mutable, non-static member variables
}

SomeDataProcessor sdp;
SomeData data1;
SomeData data2;

someObscureFunction(sdp.calc(data1, data2),
                    sdp.calc(data1, data2));

让我们考虑可能的等效代码:

Let's consider the potentially equivalent code:

bool b = sdp.calc(data1, data2);
someObscureFunction(b,b);

要使其有效,calc()函数应满足一些要求,例如,我将该属性称为_pure_const_formula_

For this to be valid, the calc() function should meet some requirements, and for the example I call the property _pure_const_formula_

A _pure_const_formula_将:

  • 不更改任何成员,静态或全局变量状态
  • 仅调用_pure_const_formula_函数
  • 也许我没有想到其他一些条件
  • Not change any member, static or global variable state
  • Call only _pure_const_formula_ functions
  • Maybe some other conditions that I don't have in mind

例如,调用随机数生成器将不符合这些要求.

For instance, calling a random number generator would not fit these requirements.

即使编译器需要递归地挖掘到被调用的函数中,编译器是否可以将第二个代码替换为第一个代码?现代编译器能够做到这一点吗?

Is the compiler allowed to replace the first code with the second one, even if it needs to dig recursively into called functions? Are modern compilers able to do this?

推荐答案

GCC具有pure 属性(用作__attribute__((pure))),它告诉编译器可以消除多余的调用.例如在strlen上.

GCC has the pure attribute (used as __attribute__((pure))) for functions which tells the compiler that redundant calls can be eliminated. It's used e.g. on strlen.

我不知道任何编译器会自动执行此操作,尤其是考虑到以下事实:要调用的函数可能无法以源代码形式提供,并且目标文件格式不包含有关函数是否纯净的元数据.

I'm not aware of any compiler doing this automatically, especially considering the fact that the functions to be called may not be available in source form, and the object file formats contain no metadata about whether a function is pure or not.

这篇关于现代C ++编译器是否可以避免在某些情况下两次调用const函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆