简体   繁体   中英

Can a compiler be instructed to elide away the copy of variant_t being returned in C++?

In my database accessing code, I wish to write a method:

variant_t GetQueryRows (...)

I would like to call it:

const variant_t result = GetQueryRows (...)

Although I can do this, the copying of the variant_t shows rather high in my profiler results. So I need to ensure that the variant_t is not copied. There is no move constructor or move assign in variant_t, and I cannot modify the source of variant_t in order to add one.

Is there anything I can do in Visual Studio 2012 using C++, aside from the obvious thing of returning the 'result' via an out parameter?

There's nothing you can do to guarantee it. If possible, the compiler will generally elide this copy via return value optimization , but there are several caveats.

Within GetQueryRows , you should have only one named variable that is returned, from only one point in the function; multiple returns, or returns that may return one value or another, break return value optimization. You cannot throw any exceptions.

If you want to guarantee the behavior, using an output parameter is the only reliable way.

Compilers will elide copying that by an optimization called return value optimization . They will be applied by compiler if it's possible, you can not force it. In addition you can use move semantics to avoid deep copies.

Don't make your program's logic rely on this kind of optimization. But, write your code somehow so that the compiler will be encouraged to apply these optimizations.

Copy ellision by return value optimization will likely occur if GetQueryRows is structured thusly:

const variant_t GetQueryRows() {
    variant_t result;  // Exactly one declaration of return value
    ...                // arbitrary code
    return result;     // Exactly one return statement.
}

Reference: http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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