简体   繁体   中英

C++ difference between passing argument from a function call or passing argument from variable

Whats the difference between this:

function1(function2());

And this:

var1 = function2();
function1(var1);

In terms of efficiency or whatever, what is the best option?

Before C++11 there is no big difference. Since move semantics were introduced the difference can be substantial. When a function needs to make a copy of its parameter it can have two overloads: one that actually does make a copy and another one that can move when the parameter is a temporary:

#include <iostream>

struct bar {};
bar b() { return {};}

struct foo {
    bar b;
    void set(const bar& in) { 
        std::cout << "copy \n";
        b = in;
    }
    void set(bar&& in){
        std::cout << "no need to copy, can move\n"; 
        b = std::move(in);
    }
};

int main() {
    foo f;
    bar b1;
    f.set(b1);
    f.set(b());
}

bar in this example is just a lightweight class, but when it is cheap to move but expensive to copy then f.set(b1) is less efficient than f.set(b()) . The caller could f.set(std::move(b1)) , but it is more clear to call f.set(b()) rather than having a moved from object hanging around.


However, already before C++11, the question you should actually ask is: Does it make sense to give a name to the result of calling function2 ? Do you need the result only to call function1 or do you need it also elsewhere? And this can be answered independently of whether you are writing ancient C++ or whether move semantics are involved. In short: Write code to be clear and readable. Concerns about efficieny are for a later stage, when you have correct and working code that you can measure and profile.

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