C ++:优化函数没有副作用 [英] C++: optimizing function with no side effects

查看:246
本文介绍了C ++:优化函数没有副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中有一种方法来声明函数没有副作用?请考虑:

Is there a way in C++ to declare that a function has no side effects? Consider:

LOG("message").SetCategory(GetCategory()); 

现在假设发布版本中的LOG宏创建了一个NullLogEntry对象,该对象的SetCategory()定义为空功能。所以基本上整个表达式可以(应该)被优化掉 - 在理论上,GetCategory()调用可能会有一些副作用,所以我想编译器不允许把它丢弃。

Now suppose that the LOG macro in release builds creates a NullLogEntry object that has SetCategory() defined as an empty function. So basically the whole expression could (and should) be optimized away -- expcept that, in theory, the GetCategory() call may have some side effects, so I guess the compiler is not permitted to just throw it away.

另一个例子可能是一个函数模板专门化,忽略它的一些(或所有)参数,但编译器不允许在调用时保存对这些参数的求值因为可能的副作用。

Another example could be a function template specialization that ignores some (or all) of its arguments, yet the compiler is not allowed to save the evaluation of such arguments at the call site due to possible side effects.

我是对吗?或者可以编译器优化掉这样的电话吗?如果没有,是否有一种方法来提示编译器这个函数没有副作用,所以如果返回值被忽略,那么整个调用可以跳过?

Am I right? Or can compilers optimize away such calls anyway? If not, is there a way to hint the compiler that this function has no side effects, so if the return value is ignored then the whole call can be skipped?

推荐答案

没有标准的方式这样做,但有些编译器有注释,你可以使用这种效果,在GCC中,您可以使用函数中的 __ attribute_pure __ 标记(或 __ attribute __((pure))该函数是 pure (即没有副作用)。这在标准C库中广泛使用,例如:

There is no standard way of doing so, but some compilers have annotations that you can use to that effect, for example, in GCC you can use the __attribute_pure__ tag in a function (alternatively __attribute__((pure))) to tell the compiler that the function is pure (i.e. has no side effects). That is used in the standard C library extensively, so that for example:

char * str = get_some_string();
for ( int i = 0; i < strlen( str ); ++i ) {
    str[i] = toupper(str[i]);
}

可由编译器优化为:

char * str = get_some_string();
int __length = strlen( str );
for ( int i = 0; i < __length; ++ i ) {
   str[i] = toupper(str[i]);
}

该函数在string.h头文件中声明为:

The function is declared in the string.h header as:

extern size_t strlen (__const char *__s)
     __THROW __attribute_pure__ __nonnull ((1));

其中 __ THROW case,它是一个C ++编译器解析函数, __ nonnull((1))告诉编译器第一个参数不应该为null(即触发一个警告,如果参数为空,并使用-Wnonnull标志)。

Where __THROW is a no throw exception in case that it is a C++ compiler parsing the function, and __nonnull((1)) tells the compiler that the first argument should not be null (i.e. trigger a warning if the argument is null and -Wnonnull flag is used).

这篇关于C ++:优化函数没有副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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