且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不通过引用传递结构体共同优化?

更新时间:2023-11-05 20:36:28

不要忘了,在C / C ++编译器需要能够编译仅在函数声明为基础,以一个函数的调用。

Don't forget that in C/C++ the compiler needs to be able to compile a call to a function based only on the function declaration.

由于呼叫者可能只使用这些信息,也没有办法为一个编译器来编译功能带你谈论的优化优势。主叫方可以不知道函数不会修改任何东西,所以它不能由参传递。由于一些呼叫者可以按值传递,由于缺乏详细的信息,该函数有假设传递由值和每个人都需要按值传递进行编译。

Given that callers might be using only that information, there's no way for a compiler to compile the function to take advantage of the optimization you're talking about. The caller can't know the function won't modify anything and so it can't pass by ref. Since some callers might pass by value due to lack of detailed information, the function has to be compiled assuming pass-by-value and everybody needs to pass by value.

请注意,即使您标记的参数为常量',编译器仍然不能进行优化,因为该功能可以撒谎,抛弃常量性(这是允许的和明确的,只要传递的对象其实不是常量)。

Note that even if you marked the parameter as 'const', the compiler still can't perform the optimization, because the function could be lying and cast away the constness (this is permitted and well-defined as long as the object being passed in is actually not const).

我认为,静态函数(或者那些在匿名命名空间),编译器可能会使得你在谈论优化,因为函数没有外部链接。只要函数的地址不传递到某些其他常规或存储于一个指针,它不应该是从其他code调用。在这种情况下,编译器可以将所有的来电者充分了解,所以我想它可以使优化。

I think that for static functions (or those in an anonymous namespace), the compiler could possibly make the optimization you're talking about, since the function does not have external linkage. As long as the address of the function isn't passed to some other routine or stored in a pointer, it should not be callable from other code. In this case the compiler could have full knowledge of all callers, so I suppose it could make the optimization.

我不知道如果有做(其实,我会感到惊讶,如果任何事,因为它可能不能经常使用)。

I'm not sure if any do (actually, I'd be surprised if any do, since it probably couldn't be applied very often).

当然,作为程序员(当使用C ++),你可以强制编译器使用常量和放大器来执行此优化; 参数只要有可能。我知道你问为什么编译器不能自动做到这一点,但我想这是未来***的事情。

Of course, as the programmer (when using C++) you can force the compiler to perform this optimization by using const& parameters whenever possible. I know you're asking why the compiler can't do it automatically, but I suppose this is the next best thing.