简体   繁体   English

C ++指针和优化

[英]C++ pointers and optimization

I have read that the C++ compiler does the optimization for you (,or at least should) and that the programmer shouldn't worry too much about it. 我已经读过C ++编译器为您进行了优化(至少应该这样做),并且程序员不必为此担心太多

But how does this compare to pointers? 但这与指针相比如何? It seems that every time you make a function you have to decide whether to use pointers or not. 似乎每次创建函数时,您都必须决定是否使用指针。 What's the reason behind this? 这是什么原因呢? Shouldn't the compiler do this for you as far as possible? 编译器是否应该尽可能为您这样做?

And isn't there a keyword which you can use in the method signature that states that the objects given as parameter won't be mutated so that the compiler could optimize stuff? 难道没有一个可以在方法签名中使用的关键字,该关键字指出不会更改作为参数给出的对象,以便编译器可以优化内容吗?

And why is(n't) there one? 为什么不在那里呢?

Using object as argument, a compiler may or may not do the copy ellision depending on many factors. 使用object作为参数,编译器可能会或可能不会执行复制省略,这取决于许多因素。 If in doubt compiler can make a safe assumption that function may want to change the argument and may avoid copy elision optimization. 如有疑问,编译器可以做出安全的假设,即函数可能要更改参数,并且可以避免复制省略优化。

Instead if you use (const) reference or a pointer, it provides stronger guarantee to the compiler that either object won't change or changes done locally in the function are required in the caller also. 相反,如果您使用(const)引用或指针,则可以为编译器提供更强大的保证 ,即对象不会更改,或者调用者也需要在函数中本地完成更改。

In general one should avoid avoid micro optimizations unless proven bottleneck using some profiling and concentrate on readability of code for better maintenance and architectural changes which can give higher optimization and can not be suggested/performed by tools. 通常,应该避免避免微优化,除非使用某些性能分析来证明瓶颈,并集中精力于代码的可读性以实现更好的维护和体系结构更改,从而可以进行更高的优化,并且不能由工具建议/执行。

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

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