Get the App
SLTechnology News&Howtos  ›  Servers  › 

What is the RVO in C++?

Shulou Source: shulou.com Published: 2022-05-31 23:39:10 09月30日 Update

This article mainly explains "what is RVO in C++". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the RVO in C++?"

Preface

Consider that there is a class such as HeavyObject, whose copy assignment is time-consuming. Which way are you used to using a function to return an object of this class? Or will you choose a certain way according to the specific situation?

/ / style 1HeavyObject func (Args param); / / style 2bool func (HeavyObject* ptr, Args param)

Both of the above methods can achieve the same goal, but the difference in intuitive experience is also very obvious:

Style 1 requires only one line of code, while style 2 requires two lines of code / / style 1HeavyObject obj = func (params); / / style 2HeavyObject obj;func (& obj, params)

However, to achieve the same goal, the cost may not be the same, depending on a number of factors, such as the features supported by the compiler, the mandatory specifications of C++ language standards, multi-team and multi-environment development, and so on.

It seems that although style 2 needs to write two lines of code, the internal cost of the function is determined, and it only depends on your current compiler. Even if you use a different compiler for function calls, there will be no extra time overhead and stability problems. For example, func is compiled using clang+libc++ internally, and the compilation environment for external calls is gcc+gnustl or vc++,. In addition to the overhead of function calls, there is no need to worry about other performance overhead and crash due to different compilation environments.

So here I mainly analyze the points that developers need to pay attention to behind style 1.

RVO

RVO is an acronym for Return Value Optimization, that is, return value optimization. NRVO is a variant of RVO. This feature is supported since RVO 11, that is to say, this optimization feature is not written into the standard, but a small number of compilers will also support RVO optimization in the development process (such as IBM Compiler? For example, Microsoft has only supported it since Visual Studio 2010.

Still take the HeavyObject class as an example, in order to understand the behavior of the compiler more clearly, the construction / destructor and copy construction, assignment operation, right constructor are implemented here, as follows

Class HeavyObject {public: HeavyObject () {cout

Tags: Function compile way compiler object result run actual clocked code copy different overhead environment support that is multiple features development Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Linux MySQL Docker macOS